******See code update in one of the posts below. Any help greatly appreciated!*******
Hello,
Beginner C++ student here, first programming class. I am trying to build a program which will accept a set of numbers from the user and output the average. However, when attempting to get the average of example 1 I get 3.5. Example two I get -0. Any help is greatly appreciated!
#include <iostream>
usingnamespace std;
int main(){
double num;
double input;
double sum = 0;
double avg;
cout << "Please enter a set of numbers. Enter a non-number to quit: "
<< endl;
cin >> num;
while (cin >> num) // When value is not a number, quit.
for(int i = 1; i <= num; i++){
cin >> input;
sum += input;
}
avg = sum / num;
cout << "average = " << avg << endl;
return 0;
}
Ah, I see what you mean. I worked with the while loop and came up with the code below. However, now I get
1
Enter a number: 1
2
Enter a number: 2
3
Enter a number: 3
4
Enter a number: 4
blah
The Average is: 2.5
Press any key to continue...
I am unsure as to why I have to enter a value prior to the program returning "Enter a number: ". However, at least I am now getting the correct average. Any help with that? Thank you so much!
#include <iostream>
usingnamespace std;
constint numToLimit = 4;
int main(){
double sum = 0;
double average = 0;
double input;
// Get 10 numbers from the user
//for (int i = 0; cin >> numToLimit; ++i)
while (cin >> input)
{
cout << "Enter a number: ";
cin >> input;
int i = 1;
i <= numToLimit;
sum += input;
}
// Get average and print it
average = sum / numToLimit;
cout << "The average is: " << average << endl;
return 0;
}
#include <iostream>
#include <string>
#include <cstdlib> // exit EXIT_FAILURE
usingnamespace std;
bool die(const string & msg);
int main(){
int numToEnter;
double sum = 0;
double average = 0;
double input;
// Get numbers from the user
cout << "Enter number of items: ";
cin >> numToEnter || die("Input failure, only numbers allowed.");
while ((cout << "Enter a number: ") && (cin >> input))
{
int i = 1;
i <= numToEnter;
sum += input;
}
// Get average and print it
average = sum / numToEnter;
cout << "The average is: " << average << endl;
return 0;
}
bool die(const string & msg)
{
cout << "Fatal Error: " << msg << endl;
exit(EXIT_FAILURE);
}