+ 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; }
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.
+ 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);
}
+ 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
+ 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?
+ 2
besides that is it fine ?
+ 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;
}