My book wants me to make a program that takes in 10 golf scores, displays them, and calculate their mean (all in different functions of course). They also want me to make it possible to terminate input if the user has less than 10 to enter. For some reason, it terminates, but sets the rest of the values at funky numbers.
#include <iostream>
usingnamespace std;
void input(double ar[], int size);
void display(constdouble ar[], int size);
double mean(constdouble ar[], int size);
int main(){
int scores = 10;
double golf[scores];
cout << "Enter up to 10 golf scores, and type any letter or word to stop if you don't have anymore to enter\n";
input(golf,scores);
display(golf,scores);
double total = mean(golf,scores);
cout << " And your average is: " << total << ".";
cin.get();
}
void input(double ar[], int size){
int i = 0;
while (cin && i<size){
cout << i+1 << ": ";
cin >> ar[i];
i++;
}
}
void display(constdouble ar[], int size){
int i = 0;
cout << "Here is what you entered for me:\n";
while (i<size){
cout << i+1 << ": ";
cout << ar[i] << "\n";
i++;
}
cin.get();
}
double mean(constdouble ar[], int size){
int i = 0;
double total = 0;
while (i<size){
total += ar[i];
i++;
}
total /=size;
return total;
}
- That's because you don't initialise your array. You've allocated space for 10 numbers, but if the user enters 7 numbers, the last 3 numbers will be set to whatever happens to be in memory at that point. Thus resulting in garbage values.
terminate input if the user has less than 10 to enter
void input(double ar[], int size)
- What happens if the user enters 7 numbers?
- Your display function still uses int scores = 10;. Likewise with your mean function.
I would recommend to use std::vector as it's just easier and more convenient to use than arrays.