looping problem

Hi guys,

For some reason when i run this program i get the wrong answers. my sum and average is doubled and my count is added too much. What did i do wrong?

#include <iostream>
#include <stdio.h>
using namespace std;

int main()
{
int count;
double average,sum,num;
count=0;
sum=0;
while(cin!=NULL)
{
cout<<"Enter a number"<<endl;
cin>>num;
sum=sum+num;
average=(sum/count);
count++;



}
cout<<"Sum: "<<sum<<endl;
cout<<"Count: "<<count<<endl;
cout<<"Average: "<<average<<endl;
}
What did i do wrong?

You looped on the state of cin and didn't bother checking to see if a particular input extraction operation was successful before using the results of that operation.

cin is not a pointer, by the way. Comparing it to NULL is conceptually wrong.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <stdio.h>
using namespace std;

int main()
{
    double sum = 0.0 ;
    unsigned count = 0;

    std::cout << "Enter a number\n" ;

    double value ;
    while ( std::cin >> value )
    {
        sum += value ;
        ++count ;
        
        std::cout << "Enter a number\n" ;
    }

    std::cout << "Sum: " << sum ;
    std::cout << "\nCount: " << count ;
    std::cout << "\nAverage: " << sum/count << '\n' ;
}

i have to use the command when cin != null though for my while loop
Topic archived. No new replies allowed.