Write a fragment of code that reads in integers from standard input, until end-of-file and sends their (floating point) average to standard output. If no numbers are input, the message “no values to average” is printed instead (while loops, end-of-file processing, mixed-mode arithmetic, basic conditional)

LANGUAGE: C++

CHALLENGE:

Write a fragment of code that reads in integers from standard input, until end-of-file and sends their (floating point) average to standard output. If no numbers are input, the message “no values to average” is printed instead (while loops, end-of-file processing, mixed-mode arithmetic, basic conditional).

SOLUTION:


float number=-1;
float count=0;
float sum=0;

while(cin.eof()==false){
    cin >> number;
    sum += number;
    count++;
}

if(number==-1){
    cout << "no values to average";
}
else{
    if (count>0)
        cout << sum/count;
}