I'm trying to run my program and when I enter say 3 it gives me a fatal error. It is suppose to calculate the avg of each value entered and output it. Would appreciate a little advise on this I'm stumped. The error says "warning C4700: uninitialized local variable 'sum' used".

I think I might haft to declare sum as an integer but that dosn't seem right if I want digits up to 2 decimal positions.

int main ()
{
	double num, sum, average; 

	cout << "Enter a value -99 to end:"; 
	cin >> num; 

	while (num != -99)
	{
		sum = sum + num; 
		average = sum/num; 

		cout << "The average is:" << setprecision (2) << (double)average << endl << endl; 

		cout << "Enter another value -99 to end:"; 
		cin >> num; 
	}
	return 0; 
}
int main ()
{
        double num = 0.0, sum = 0.0, average=0.0; 

        cout << "Enter a value -99 to end:"; 
        cin >> num; 

        while (num != -99)
        {
                sum = sum + num; 
                average = sum/num; 

                cout << "The average is:" << setprecision (2) << (double)average << endl << endl; 

                cout << "Enter another value -99 to end:"; 
                cin >> num; 
        }
        return 0; 
}

I'm trying to run my program and when I enter say 3 it gives me a fatal error. It is suppose to calculate the avg of each value entered and output it. Would appreciate a little advise on this I'm stumped. The error says "warning C4700: uninitialized local variable 'sum' used".

I think I might haft to declare sum as an integer but that dosn't seem right if I want digits up to 2 decimal positions.

int main()
{
	double num = -99, sum = 0, average = 0, count = 0;
	std::cout << "Enter a value -99 to end:"; 
	std::cin >> num; 

	while (num != -99)
	{
                                count++;
		sum += num; 
		average = sum/count; 

		std::cout << "The average is:" << setprecision (2) << (double)average << endl << endl; 

		cout << "Enter another value -99 to end:"; 
		cin >> num; 
	}
	return 0;
}

That should do it.

Thanx...
Sean

Thanks Sean didn't realize to add an extra variable. I couldn't edit I figure the = 0.0 for the variables but thanks guys!

To all of you, floating point values are rarely exact. Therefore testing with == will rarely work.

For example, if you entered 46, the actual value stored in the variable might be 46.000001 or 45.9999997, neither of which is equal to 46.

To all of you, floating point values are rarely exact. Therefore testing with == will rarely work.

For example, if you entered 46, the actual value stored in the variable might be 46.000001 or 45.9999997, neither of which is equal to 46.

Correct, it is common to define a 'delta' which is the amount of error you wish to tolerate, and to correct the value as it drifts.

Thanx...
Sean

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.