loop error problem PLEASE help :)

Write a program that will compute the average of a set of decimal numbers provided by the user. The program will ask the user to enter numbers one at a time. The user will enter numbers and the program will keep a count of the numbers entered. At the end, the program will display the sum, the count and the average of the numbers. See Test section below for test data.

This is what i have but it is not functioning properly. after the second time i am asked a number the program gets an error and asks to quit. Help please i have no idea how to fix this.

#include <iostream>

using namespace std;

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

}
cout<<"Sum: "<<sum<<endl;
cout<<"Count: "<<count<<endl;
cout<<"Average: "<<average<<endl;
}
Last edited on
hi dear greatallan,
you have not initialized the sum variable to 0,that means sum=0;
therefore sum contains some garbage value


You can solve this using C as follows:

#include<stdio.h>
int main()
{
float num,sum,avg;
int count;

count=0;
sum=0.0;
while(scanf("%f",&num)==1)
{
count++;
sum=sum+num;
}
avg=sum/count;
printf("This is %f",avg);
printf("This is %f",sum);
printf("This is %d",count);
return 0;
}
i initialized the sum to 0 and it made no difference it still freezes and prevents the program from working after the 2nd time it asks for the number
Last edited on
Topic archived. No new replies allowed.