+ 1

Need help finding error in persons code

#include <iostream> using namespace std; in main() { int numCount, total; double average; cout << "How many numbers do you want to average? " ; cin >> numCount; for (int count =0; count < numcount; count++) { int num; cout << "Enter a number: " ; cin >> num; total += num; count ++; } average = total / numCount; cout << "The average is" << average << endl; system ("pause"); return 0; }

13th Mar 2017, 12:44 AM
Hunter isaacs
6 ответов
+ 11
the / operator's behavior depends on the operands' type. In your case you have int / int and it will return the result of floor division ( 7/2 = 3 ). To return the real average either cast or declare the total as double.
13th Mar 2017, 12:53 AM
Nikolay Nachev
Nikolay Nachev - avatar
+ 9
I don't know C++ I can demonstrate in C #include<stdio.h> main() { int n , i ; double avg , sum = 0 ,o ; puts("Enter number of observation"); scanf("%d",&n); puts("Enter your Observations"); for(i=1;i<n;i++) { scanf("%f",&o); sum += o; } avg = sum/n; printf("The average is %f ",avg); }
13th Mar 2017, 4:11 AM
Shirious
Shirious - avatar
+ 7
#include <iostream> #include <stdlib.h> using namespace std; int main() { int numCount, total; double average; total=0; cout << "How many numbers do you want to average? " ; cin >> numCount; for (int count =0; count < numCount; count++) { int num; cout << "Enter a number: " ; cin >> num; total += num; } average = total / numCount; cout << "The average is : " << average << endl; system ("pause"); return 0; } it is a correct code
13th Mar 2017, 3:29 AM
Amar Dahake
+ 6
I spotted a 1, maybe 2 if we count the typo,errors there. Instead of asking around, why not learn how to use a debugger?
13th Mar 2017, 1:19 AM
Wen Qin
Wen Qin - avatar
+ 2
besides that is it fine ?
13th Mar 2017, 1:04 AM
Hunter isaacs
+ 2
#include <iostream> using namespace std; in main() { int numCount, total, num; double average; cout << "How many numbers do you want to average? " ; cin >> numCount; for (int count =0; count < numcount; count++){ cout << "Enter a number: " ; cin >> num; total += num; // delete this line count ++; } //average = total / numCount; average = double(total) / double(numCount); cout << "The average is" << average << endl; system ("pause"); return 0; }
13th Mar 2017, 6:11 AM
देवेंद्र महाजन (Devender)
देवेंद्र महाजन (Devender) - avatar