Can't display average value, returns "nan(ind)" or "0"

Hi guys, I apologize in advance if this problem is an elementary one. I am n00b in programming and I started learning C++ today. Never programmed anything before.

The program is supposed to ask for several numbers from the user. There is no limit of how many numbers the user can input. So the user inputs random numbers and presses a letter and hits ENTER. Program stores all values, does the sum of all variables and also counts the number of variables entered. Finally, it prints on the standard output the average. The annoying part here is that I can't get the average to be displayed correctly. Sometimes it returns me a "0" or a "-nan(ind)" value that I don't even know what that is. I wish I could see a decimal average there... So, can anyone help me out?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
int main()
{
        int sum = 0, value = 0;
	/* Program will read input values as long as those
	 * values are numbers and print the sum in the end. */
	std::cout << "Please input several numbers you want to add together." << std::endl;
	std::cout << "When done, press any letter and hit ENTER." << std::endl;
	while (std::cin >> value)// The condition holds the value of several input numbers.
		sum += value;	 //Equivalent of writting "sum = sum + value".
	std::cout << "The sum of all those numbers is: " << sum << std::endl;
	system("pause");

     int input, sum2 = 0, counter = 1;
     float average;
     std::cout << "Please input several numbers to find their average. " << std::endl;
     std::cout << "When done, press any letter and hit ENTER." << std::endl;
     while (std::cin >> input)
          sum2 += input, ++counter;
     average = (float)sum2 / (float)counter;
     std::cout << "The average of those numbers is: " << average << std::endl;
     /* I KEEP GETTING "0" or "-nan(ind)" instead of the average here.
      * Program appears to not wait for my inputs and runs straight
      * to the end basically dividing the sum2 by counter. */
     system("pause");
     return 0;
}


edited: Sorry, there is two parts. The first part of the code until the first "pause" runs fine. It's in the second part that I have problems. Interestingly enough, when I copy and past just the second portion into a brand new program with just that code inside the main() function, it works and gives me the average in decimals. I don't get it :(
Last edited on
The comma operator is a binary operator that returns the result of the second operand.

This means
 
sum2 += input, ++counter;
is actually the same as
 
sum2 += ++counter;

EDIT: I was wrong about the above but I recommend using semicolons to separate your statements anyway.


Another problem is that the counter starts at 1 so it will be one more than the actual number of values inputted. This causes the average to be calculated incorrectly.
Last edited on
Using the full code as above, both parts, I get an error like "-nan(ind)" if I attempt to start the counter at 1. If I start it at 0 as you said, it returns a "0" instead.

Try this, if you cut off the first part of the code and just include the second part inside the main() it works as supposed to. I start at 0 or 1 the counter and it doesn't matter, it always runs smooth. I don't understand why this happens.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>\

int main()
{
    int sum = 0, value = 0;
    std::cout << "Please input several numbers you want to add together.\n" ; // << std::endl;
    std::cout << "When done, press any letter and hit ENTER.\n" ; // << std::endl;
    while (std::cin >> value)// The condition holds the value of several input numbers.
        sum += value;	 //Equivalent of writting "sum = sum + value".
    std::cout << "The sum of all those numbers is: " << sum << "\n\n" ; // std::endl;

    // std::cin is in a failed state at this point. it won't accept any input while in this state
    std::cin.clear() ; // **** clear the failed state
    std::cin.ignore( 1000000, '\n' ) ; // **** extract and discard the non-numeric input remaining in the buffer

    int input, sum2 = 0, counter = 0 ; // = 1; *******
    std::cout << "Please input several numbers to find their average.\n" ; // << std::endl;
    std::cout << "When done, press any letter and hit ENTER.\n" ; // << std::endl;

    while (std::cin >> input)
        sum2 += input, ++counter;

    if( counter != 0 ) // *******
    {
        const double average = double(sum2) / counter;
        std::cout << "The average of those numbers is: " << average << std::endl;
    }
}
Last edited on
Thank you all for the help!

JLBorges: I didn't know about std::cin.clear() and std::cin.ignore(1000000, '\n')
I understand now how to cin.clear a failed input state, but:
-What is that 1000000 value inside the cin.ignore used for?
-Can it be some other number as well?
-Why are you using const double? Can't it be the float type that I originally used?
Last edited on
The 1000000 is just a large enough number that is adequate for our purpose: extract and discard characters up to a maximum of 1000000 characters or till a new-line character is extracted and discarded.

std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
Extract and discard an unlimited number of characters till either a new-line character is extracted and discarded or an end of file condition is encountered.
http://en.cppreference.com/w/cpp/io/basic_istream/ignore


> -Why are you using const double? Can't it be the float type that I originally used?

Use double as the default floating point type.

float and double have the same performance characteristics on modern processors; though double has a higher precision.
Last edited on
Topic archived. No new replies allowed.