The question is
Design the grade processing program to use functions and an array. Let user enter number of grades (set the maximum to 50). Store grades in an array. Create a separate function for each calculation (total of 3 functions): 1) average grade, 2) maximum grade, 3) number of grades above the average. Display all results.
I think I got the main part, but I'm having trouble with how to write the functions, the functions are outputting one for some reason, and I'm having trouble writing the max function or how to start it.
#include <iostream>
using namespace std;
double average(double x[], int n);
double maximum(double x[], int n);
int nAboveAvg(double x[], int n);
int main()
{
double grades[50];
int ngrades;
cout<<"How many grades? (max = 50)";
cin>>ngrades;
//create for loop to get grades from user
for(int i = 0; i<ngrades; i++)
{
cout<<"Enter grade ";
cin>> grades[i];
}
//call the functions
double avg = average(grades, ngrades);
double max = maximum(grades, ngrades);
int nAbove = nAboveAvg(grades, ngrades);
//display results
cout<<"Average = "<<avg<<endl;
cout<<"# above average = "<<nAbove<<endl;
}
double average(double x[], int npts) //define the functon to recieve the array
{
double sum = 0;
for(int k = 0; k<npts; k++)
{
sum = sum +x[k];
}
return sum / npts;
}
double maximum(double x[], int npts)
{
double max = 0;
for(int i = 0; i<npts; i++)
{
if(max == npts)
{
return max;
}
if(max < npts)
{
return npts;
}
}
}
int nAboveAvg(double x[], int npts)
{
int nAboveAvg = 0;
for(int i = 0; i<npts;i++)
{
if(x[i] > npts)
{
nAboveAvg++;
}
}
return nAboveAvg;
}
Incorrect Printing
//call the functions
double avg = average(grades, ngrades);
double max = maximum(grades, ngrades);
int nAbove = nAboveAvg(grades, ngrades);
Notice that you define variables named avg and nAbove.
//display results
cout<<"Average = "<<average<<endl;
cout<<"# above average = "<<nAboveAvg<<endl;
But then you use average and nAboveAvg (the functions) when you attempt to print the results.
The correct version here would be:
cout << "Average = " << avg << endl;
cout << "# above average = " << nAbove << endl;
Compiler Warnings
When I try to compile this, the compiler emits a number of warnings. e.g.
main.cpp: In function 'int main()':
main.cpp:29:24: warning: the address of 'double average(double*, int)' will always evaluate as 'true' [-Waddress]
cout<<"Average = "<<average<<endl;
or
main.cpp:24:11: warning: unused variable 'avg' [-Wunused-variable]
double avg = average(grades, ngrades);
It is a good idea not to ignore those warnings.
Count Above Average
if(x[i] > npts)
{
nAboveAvg++;
}
You compare the value at position i with number of input values.
However, you should be comparing value at position i with the average of all the values. Hence
int nAboveAvg(double x[], int npts)
{
int count = 0;
double avg = average(x, npts);
for (int i(0); i < npts; ++i) {
if (x[i] > avg) {
++count;
}
}
return count;
}
Refactoring
You may now notice that in our program we end up calculating the average value twice. We can fix this by making our function more general -- instead of counting number of values above average, let's count the number of values above arbitrary target passed as a parameter.
int count_above(double x[], int npts, double target)
{
int count = 0;
for (int i(0); i < npts; ++i) {
if (x[i] > target) {
++count;
}
}
return count;
}
Now we can write
//call the functions
double avg = average(grades, ngrades);
double max = maximum(grades, ngrades);
int nAbove = count_above(grades, ngrades, avg);
Maximum Value
Let's think about the algorithm, and start from simplest case -- only one value in the array. In this scenario the first value is also the maximum.
double max = x[0];
Knowing that, let's consider how to find the maximum when there are 2 values in the input array. We already know the maximum of all the values before the second value. Therefore
if (x[1] > max) {
max = x[1];
}
Next step, input array with 3 values. Again, we already know the maximum of all the values before the third value. Therefore
if (x[2] > max) {
max = x[2];
}
We can see a pattern repeating here, which we can wrap in a loop.
double maximum(double x[], int npts)
{
if (npts <= 0) {
exit(-1); // Error...
}
double max = x[0];
for (int i(1); i < npts; ++i) {
if (x[i] > max) {
max = x[i];
}
}
return max;
}
Validating Input
You don't have any validation of the input passed to your functions, yet there are some obvious cases that need to be accounted for.
In all of your functions, what should happen when the npts is negative?
What's the average value of a 0 elements?
What's the maximum value of 0 elements?
A very simple way to handle those cases would be to return some special value as a result. You then have to check the results for this value every time you call the function. In many cases it may be hard to select an appropriate value for this.
Another possibility that would be accepted at a beginner level, would be simply printing some error message to console, and exiting the program. For example
if (npts <= 0) {
cerr << "Too few values in input array." << endl;
exit(-1); // Error...
}
The proper C++ approach would be to throw an exception, for example std::invalid_argument. For example
#include <stdexcept>
// ....
if (npts <= 0) {
throw std::invalid_argument("Too few values in input array.);
}
The "average" function looks good. In the last 2 lines in main, I think you want to output avg instead of average (because average is the name of the function, not the name of the variable that holds the computed value). Similarly, output nAbove instead of nAboveAvg.
The maximum function looks like an empty implementation. I don't think that will compile because it needs to (at least) return a double value.
In the nAboveAvg function, "x[i] > npts" seems like the wrong test. I think you want to compare x[i] to avg (you will want to pass avg into this function as an argument.
Related
Program in C++ that takes 3 numbers and send them to a function and then calculate the average function of these 3 numbers.
I know how to do that without using a function ,for example for any n numbers I have the following program:
#include<stdio.h>
int main()
{
int n, i;
float sum = 0, x;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("\n\n\nEnter %d elements\n\n", n);
for(i = 0; i < n; i++)
{
scanf("%f", &x);
sum += x;
}
printf("\n\n\nAverage of the entered numbers is = %f", (sum/n));
return 0;
}
Or this one which do that using arrays:
#include <iostream>
using namespace std;
int main()
{
int n, i;
float num[100], sum=0.0, average;
cout << "Enter the numbers of data: ";
cin >> n;
while (n > 100 || n <= 0)
{
cout << "Error! number should in range of (1 to 100)." << endl;
cout << "Enter the number again: ";
cin >> n;
}
for(i = 0; i < n; ++i)
{
cout << i + 1 << ". Enter number: ";
cin >> num[i];
sum += num[i];
}
average = sum / n;
cout << "Average = " << average;
return 0;
}
But is it possible to use functions?if yes then how? thank you so much for helping.
As an alternative to using fundamental types to store your values C++ provides std::vector to handle numeric storage (with automatic memory management) instead of plain old arrays, and it provides many tools, like std::accumulate. Using what C++ provides can substantially reduce your function to:
double avg (std::vector<int>& i)
{
/* return sum of elements divided by the number of elements */
return std::accumulate (i.begin(), i.end(), 0) / static_cast<double>(i.size());
}
In fact a complete example can require only a dozen or so additional lines, e.g.
#include <iostream>
#include <vector>
#include <numeric>
double avg (std::vector<int>& i)
{
/* return sum of elements divided by the number of elements */
return std::accumulate (i.begin(), i.end(), 0) / static_cast<double>(i.size());
}
int main (void) {
int n; /* temporary integer */
std::vector<int> v {}; /* vector of int */
while (std::cin >> n) /* while good integer read */
v.push_back(n); /* add to vector */
std::cout << "\naverage: " << avg(v) << '\n'; /* output result */
}
Above, input is taken from stdin and it will handle as many integers as you would like to enter (or redirect from a file as input). The std::accumulate simply sums the stored integers in the vector and then to complete the average, you simply divide by the number of elements (with a cast to double to prevent integer-division).
Example Use/Output
$ ./bin/accumulate_vect
10
20
34
done
average: 21.3333
(note: you can enter any non-integer (or manual EOF) to end input of values, "done" was simply used above, but it could just as well be 'q' or "gorilla" -- any non-integer)
It is good to work both with plain-old array (because there is a lot of legacy code out there that uses them), but equally good to know that new code written can take advantage of the nice containers and numeric routines C++ now provides (and has for a decade or so).
So, I created two options for you, one use vector and that's really comfortable because you can find out the size with a function-member and the other with array
#include <iostream>
#include <vector>
float average(std::vector<int> vec)
{
float sum = 0;
for (int i = 0; i < vec.size(); ++i)
{
sum += vec[i];
}
sum /= vec.size();
return sum;
}
float average(int arr[],const int n)
{
float sum = 0;
for (int i = 0; i < n; ++i)
{
sum += arr[i];
}
sum /= n;
return sum;
}
int main() {
std::vector<int> vec = { 1,2,3,4,5,6,99};
int arr[7] = { 1,2,3,4,5,6,99 };
std::cout << average(vec) << " " << average(arr, 7);
}
This is an example meant to give you an idea about what needs to be done. You can do this the following way:
// we pass an array "a" that has N elements
double average(int a[], const int N)
{
int sum = 0;
// we go through each element and we sum them up
for(int i = 0; i < N; ++i)
{
sum+=a[i];
}
// we divide the sum by the number of elements
// but we first have to multiply the number of elements by 1.0
// in order to prevent integer division from happening
return sum/(N*1.0);
}
int main()
{
const int N = 3;
int a[N];
cin >> a[0] >> a[1] >> a[2];
cout << average(a, N) << endl;
return 0;
}
how to do that without using a function
Quite simple. Just put your code in a function, let's call it calculateAverage and return the average value from it. What should this function take as input?
The list of numbers (array of numbers)
Total numbers (n)
So let's first get the input from the user and put it into the array, you have already done it:
for(int i = 0; i < n; ++i)
{
cout << i + 1 << ". Enter number: ";
cin >> num[i];
}
Now, lets make a small function i.e., calculateAverage():
int calculateAverage(int numbers[], int total)
{
int sum = 0; // always initialize your variables
for(int i = 0; i < total; ++i)
{
sum += numbers[i];
}
const int average = sum / total; // it is constant and should never change
// so we qualify it as 'const'
//return this value
return average
}
There are a few important points to note here.
When you pass an array into a function, you will loose size information i.e, how many elements it contains or it can contain. This is because it decays into a pointer. So how do we fix this? There are a couple of ways,
pass the size information in the function, like we passed total
Use an std::vector (when you don't know how many elements the user will enter). std::vector is a dynamic array, it will grow as required. If you know the number of elements beforehand, you can use std::array
A few problems with your code:
using namespace std;
Don't do this. Instead if you want something out of std, for e.g., cout you can do:
using std::cout
using std::cin
...
or you can just write std::cout everytime.
int n, i;
float num[100], sum=0.0, average;
Always initialize your variables before you use them. If you don't know the value they should be initialized to, just default initialize using {};
int n{}, i{};
float num[100]{}, sum=0.0, average{};
It is not mandatory, but good practice to declare variables on separate lines. This makes your code more readable.
I have created a program that prompts a user to enter a data set. The program stores and sorts the data, then computes a variance and the standard deviation of the array. However, I am not getting the correct computations for variance and standard deviation (the answer is slightly off). Anyone know what the issue seems to be?
#include <iostream>
#include <iomanip>
#include <array>
using namespace std;
//function declarations
void GetData(double vals[], int& valCount);
void Sort(double vals[], int& valCount);
void printSort(double vals[], int& valCount);
double Variance(double vals[], int valCount);
double StandardDev(double vals[], int valCount);
double SqRoot(double value); //use for StandardDev function
//function definitions
int main ()
{
double vals = 0;
int valCount = 0; //number of values to be processed
//ask user how many values
cout << "Enter the number of values (0 - 100) to be processed: ";
cin >> valCount;
//process and store input values
GetData(&vals, valCount);
//sort values
Sort(&vals, valCount);
//print sort
cout << "\nValues in Sorted Order: " << endl;
printSort(&vals, valCount);
//print variance
cout << "\nThe variance for the input value list is: " << Variance(&vals, valCount);
//print standard deviation
cout << "\nThe standard deviation for the input list is: " <<StandardDev(&vals, valCount)<< endl;
return 0;
}
//prompt user to get data
void GetData(double vals[], int& valCount)
{
for(int i = 0; i < valCount; i++)
{
cout << "Enter a value: ";
cin >> vals[i];
}
}
//bubble sort values
void Sort(double vals[], int& valCount)
{
for (int i=(valCount-1); i>0; i--)
for (int j=0; j<i; j++)
if (vals[j] > vals[j+1])
swap (vals[j], vals[j+1]);
}
//print sorted values
void printSort(double vals[], int& valCount)
{
for (int i=0; i < valCount; i++)
cout << vals[i] << "\n";
}
//compute variance
double Variance(double vals[], int valCount)
{
//mean
int sum = 0;
double mean = 0;
for (int i = 0; i < valCount; i++)
sum += vals[i];
mean = sum / valCount;
//variance
double squaredDifference = 0;
for (int i = 0; i < valCount; i++)
squaredDifference += (vals[i] - mean) * (vals[i] - mean);
return squaredDifference / valCount;
}
//compute standard deviation
double StandardDev(double vals[], int valCount)
{
double stDev;
stDev = SqRoot(Variance(vals, valCount));
return stDev;
}
//compute square root
double SqRoot(double value)
{
double n = 0.00001;
double s = value;
while ((s - value / s) > n)
{
s = (s + value / s) / 2;
}
return s;
}
There was quite a bit wrong with the code that was causing your errors. Type mismatches, but more importantly, you never created an array to store the values. You treated a plain double like an array and got lucky your program never crashed on you.
Below is a working version of your code, verified with a made up data set and Excel. I left as much of your code there as possible, just commented out when appropriate. If I commented it out, I didn't make any changes to it, so there may still be errors.
Vector over array in this case. You don't know the size up front (at compile time), and vectors are easier than dynamic arrays. You also never had an array. Vectors also know how big they are, so you don't need to pass the size around.
Type mismatches. Your functions keep expecting an array of doubles, but your sum was an int, among many other mismatches. You were also passing a plain double like it was an array, writing in memory that wasn't yours to change like that.
Best practices to start now. Stop with using namespace std;. Just qualify your names when needed, or be more specific with lines like using std::cout; at the top of a function. Your naming was all over the place. Pick a naming scheme and stick with it. Names starting with a capital letter are generally reserved for classes or types.
#include <iomanip>
#include <iostream>
// #include <array> // You never actually declared a std::array
#include <vector> // You don't know the size ahead of time, vectors are the
// right tool for that job.
// Use what's available
#include <algorithm> // std::sort()
#include <cmath> // std::sqrt()
#include <numeric> // std::accumulate()
// function declarations
// Commented out redundant functions, and changed arguments to match
void get_data(std::vector<double>& vals);
// void Sort(double vals[], int& valCount);
void print(const std::vector<double>& vals);
double variance(const std::vector<double>& vals);
double standard_dev(const std::vector<double>& vals);
// double SqRoot(double value); //use for StandardDev function
// function definitions
int main() {
int valCount = 0; // number of values to be processed
// ask user how many values
std::cout << "Enter the number of values (0 - 100) to be processed: ";
std::cin >> valCount;
std::vector<double> vals(valCount, 0);
// Was just a double, but you pass it around like it's an array. That's
// really bad. Either allocate the array on the heap, or use a vector.
// Moved to after getting the count so I could declare the vector with
// that size up front instead of reserving later; personal preference.
// process and store input values
get_data(vals);
// sort values
// Sort(&vals, valCount);
std::sort(vals.begin(), vals.end(), std::less<double>());
// The third argument can be omitted as it's the default behavior, but
// I prefer being explicit. If compiling with C++17, the <double> can
// also be omitted due to a feature called CTAD
// print sort
std::cout << "\nValues in Sorted Order: " << '\n';
print(vals);
// print variance
std::cout << "\nThe variance for the input value list is: " << variance(vals);
// print standard deviation
std::cout << "\nThe standard deviation for the input list is: "
<< standard_dev(vals) << '\n';
return 0;
}
// prompt user to get data
void get_data(std::vector<double>& vals) {
for (unsigned int i = 0; i < vals.size(); i++) {
std::cout << "Enter a value: ";
std::cin >> vals[i];
}
}
// //bubble sort values
// void Sort(double vals[], int& valCount)
// {
// for (int i=(valCount-1); i>0; i--)
// for (int j=0; j<i; j++)
// if (vals[j] > vals[j+1])
// swap (vals[j], vals[j+1]);
// }
// print sorted values
void print(const std::vector<double>& vals) {
for (auto i : vals) {
std::cout << i << ' ';
}
std::cout << '\n';
}
// compute variance
double variance(const std::vector<double>& vals) {
// was int, but your now vector is of type double
double sum = std::accumulate(vals.begin(), vals.end(), 0);
double mean = sum / static_cast<double>(vals.size());
// variance
double squaredDifference = 0;
for (unsigned int i = 0; i < vals.size(); i++)
squaredDifference += std::pow(vals[i] - mean, 2);
// Might be possible to get this with std::accumulate, but my first go didn't
// work.
return squaredDifference / static_cast<double>(vals.size());
}
// compute standard deviation
double standard_dev(const std::vector<double>& vals) {
return std::sqrt(variance(vals));
}
// //compute square root
// double SqRoot(double value)
// {
// double n = 0.00001;
// double s = value;
// while ((s - value / s) > n)
// {
// s = (s + value / s) / 2;
// }
// return s;
// }
EDIT: I did figure out the variance with an accumulator. It does require knowledge of lambdas (anonymous functions, functors). I compiled to the C++14 standard, which has been the default of major compilers for a while now.
double variance(const std::vector<double>& vals) {
auto meanOp = [valSize = vals.size()](double accumulator, double val) {
return accumulator += (val / static_cast<double>(valSize));
};
double mean = std::accumulate(vals.begin(), vals.end(), 0.0, meanOp);
auto varianceOp = [mean, valSize = vals.size()](double accumulator,
double val) {
return accumulator +=
(std::pow(val - mean, 2) / static_cast<double>(valSize));
};
return std::accumulate(vals.begin(), vals.end(), 0.0, varianceOp);
}
mean = sum / valCount; in Variance will be computed using integer math, then converted to a double. You need to convert to double first:
mean = double(sum) / valCount;
Your SqRoot function calculates an approximate value. You should use std::sqrt instead which will be faster and more accurate.
I filled an array with 30 random numbers and calculated average. I want to display how many numbers are higher than the average. I tried making a function "aboveAverage" and check if the numbers are higher than the average and than just increase the count "num_over_average++". The problem is I don't know how to pass a value "avg" from function to another function.
#include <iostream>
#include <ctime>
using namespace std;
const int n = 30;
void fillArray(int age[], int n) {
srand(time(NULL));
for (int index = 0; index < n; index++) {
age[index] = (rand() % 81) + 8;
}
}
void printArray(int age[], int n) {
for (int index = 0; index < n; index++) {
cout << age[index] << endl;
}
}
double printAverage(int age[], int n) {
double sum;
double avg = 0.0;
for (int i = 0; i < n; i++) {
sum = sum + age[i];
}
avg = ((double) sum) / n;
cout << avg << endl;
return avg;
}
void aboveAverage(int age[], int n) {
double avg;
int num_over_average = 0;
for(int i = 0; i < n; i++){
if(age[i] > avg) {
num_over_average++;
}
}
cout<<num_over_average;
}
int main(int argc, char *argv[]) {
int age[n];
fillArray(age, n);
cout << "array: " << endl;
printArray(age, n);
cout << endl;
aboveAverage(age, n);
//example: Days above average: 16
}
This should be a comment, but I don't have enough reps :(
Change aboveAverage to void aboveAverage(int age[], int n, double avg)
Return avg from printAverage function
Change the last part of your main code to
double avg;
avg = printAverage(age, n);
aboveAverage(age, n, avg);
Hope this helps!
You have two solutions using your code:
Either you call printAverage() to initialise avg in aboveAverage() :
void aboveAverage(int age[], int n) {
double avg = printAverage();
...
}
Or you pass the average at parameter of aboveAverage() after having computed it with printAverage() :
void aboveAverage(int age[], int n, double avg) {
...
}
If you use the standard library you can do that with two lines of code:
double average = std::accumulate(std::begin(age), std::end(age), 0.0) / std::size(age);
int above_average = std::count_if(std::begin(age), std::end(age),
[average](double value) { return average < value; });
Okay, you might count that as three lines.
One major advantage of this approach over the code in the question is that you can change the container type to, say, vector<double> without having to change any of this code.
Well is pretty simple but dependent on your situation, I'll elaborate.
I'm the case when it's part of a bigger function (do-somthing())
You could calculate the average value like so and pass it to your "aboveAverage" function and print it:
double n_average = printAverage(nArr_ages, n_agesArraySize);
aboveAverage(nArr_ages, n_agesArraySize, n_averag);
Myself would probably rewrite the printAverage function as two functions, one that returns the average value based on the array and another that prints it not both at once because it violates the SOLID principals of a single responsibility and that a function name should reflect exactly what it does, in this case maybe calculateAverage or getAverageAge or any other appropriate name will do (try and name your functions like the english language so your code will be read like a song.
For example:
const size_t n = 30;
double calculateAverage(int nArr_ages[], int n_agesArraySize) {
double sum = 0.0;
double avg = 0.0;
for (int indexInArray = 0; indexInArray < n_agesArraySize; indexInArray++) {
sum = sum + age[indexInArray];
}
average = ((double) sum) / n_agesArraySize;
return average;
}
int aboveAverageCells(int ages[], int n_agesArraySize ) {
double average = calculateAverage(ages, n);
int num_over_average = 0;
for(int indexInArray = 0; indexInArray < n_agesArraySize; indexInArray++) {
if(ages[indexInArray] > avg) {
num_over_average++;
}
}
return num_over_average;
}
Now just call them in order, save the returned values to local variables in the main function and print using cout also locally in main.
As a side note next time maybe choose different names for the const and the local functions variable for the array size.
I tried to calculate average and when I enter 1 2 3 0 , the average is 2.00 but when I enter 10 20 90 100 0,the average is 227871776.00. I am not able to identify what is going wrong here. I feel like my sum and count is not working properly but I can't figure out why.
double calculateAverage(int numbers[], int count )
{
int sum = 0;
double average;
while (count < arraysize && numbers[count] != 0)
{
count ++;
}
for (int i= 0 ; i < count; i++)
{
sum += numbers[i];
}
average = static_cast<double>(sum) /count;
return average;
}
Why bother even making your own count loop, when you have std:accumulate.
#include <numeric>
#include <iostream>
double calculateAverage(int numbers[], size_t count)
{
int sum = std::accumulate(numbers, numbers + count, 0);
return sum / count;
}
int main()
{
//int numbers[] = {1, 2, 3, 4, 5};
int numbers[] = {10, 20, 90, 100};
std::cout << "average is " <<
calculateAverage(numbers, sizeof(numbers) / sizeof(int)) << '\n';
}
Your code was quite confused. Why pass a count if you're going to count the array anyway? Also 0 is a valid value in the array and so it makes a flawed sentinel value.
#include<iostream>
using namespace std;
double calculateAverage(int numbers[], int count )
{
int sum = 0; //sum is used to add all the values in the array
double average;
for (int i= 0 ; i < count; i++)
sum += numbers[i];
average = static_cast<double>(sum) /count;
return average;
}
int main()
{
int lim; //size of the array
cout<<"Enter the number of elements in array\n";
cin>>lim;
cout<<"Enter the values \n";
int num[lim]; //the array is initialized to desired size
for(int i=0;i<lim;i++)
cin>>num[i]; //the values are taken from user
cout<<"\nAverage = "<<calculateAverage(num,lim)<<"\n"; //the array and the size of array is passed to calculate average function or you can even calculate size of array using (sizeof(array)/sizeof(array[firstelement])
return 0;
}
Recreate the code overall
It is hard to understand (your code).
Mine:
double calculateAverage(double numbers[], double count )
{
double sum = 0;
double average=0;
for(int counter=0;counter<count;counter++)
{
sum+=numbers[counter];
}
cout<<sum<<"\n";
average=sum/count;
return average;
}
Explaination:
First the function will take an array of double
and count is how many is there in the array (I tried to stick into your code)
The for loop runs based on the count variable.
the sum adds the value of the element in the array numbers.
Divide to get the average.
numbers[count] != 0 could produce errors when you have 0 appear earlier in the array. Also, where do you initialize arraysize? It could be null somehow or a very weird number. I recommend calling the numbers length instead. But there's no reason to use the while loop bc you have an array size already known
I'm trying to pass a simple array through a function to compute the mean.
int main()
{
int n = 0; // the number of grades in the array
double *a; // the array of grades
cout << "Enter number of scores: ";
cin >> n;
a = new double[n]; // the array of grades set
// to the size of the user input
cout << "Enter scores separated by blanks: ";
for(int i=0; i<n; i++)
{
cin >> a[i];
}
computeMean(a, n);
}
double computeMean (double values[ ], int n)
{
double sum;
double mean = 0;
mean += (*values/n);
return mean;
}
Right now the code is only taking the mean of the last number that was inputted.
There's no loop in your function. It should be something like:
double sum = 0;
for (int i = 0; i != n; ++i)
sum += values[i];
return sum / n;
I'm surprised your current version only takes the last number, it should only take the first number, since *values is the same as values[0].
A better solution uses idiomatic C++:
return std::accumulate(values, values + n, 0.0) / n;
std::accumulate should do the trick.
#include <numeric>
double computeMean (double values[ ], int n) {
return std::accumulate( values, values + n, 0. ) / n;
}
Is this a homework question?
You nead to step through all of the values in your array. You're currently outputting the first number in the array divided by the number of items.