Home > Mobile >  Varied Amount of Input Data
Varied Amount of Input Data

Time:09-23

Statistics are often calculated with varying amounts of input data. Write a program that takes any number of non-negative integers as input, and outputs the max and average. A negative integer ends the input and is not included in the statistics.

Ex: When the input is:

15 20 0 5 -1

the output is:

20 10

You can assume that at least one non-negative integer is input.

#include <iostream>
using namespace std;

int main() {
   int count = 0;
   int max = 0;
   int total = 0;
   int num;
   int avg;
   
   cin >> num;
   
   while (num >= 0) {
      count  ;
      total  = num;
      
      if (num > max){
         max = num;
      }
      cin >> num;
   }
   
   avg = total / count;
   cout << avg << " " << max;
   
   return 0;
}

I have been working on this problem for a while and I am currently stuck why there isn't any output. I feel like I didn't write the while loop correctly but can't seem to figure out how to fix it. Any help is appreciated.

CodePudding user response:

After start, program immediately stops waiting for user input. In order to see an output user has to enter at least one positive integer, press Enter key, enter negative integer and press Enter key once again

CodePudding user response:

Hello I rewrote your code, try with this:

int i=0, max, total = 0, avg, num, temp;
cout<<"num of elements"<<endl;
cin>>num;

while(i<num){
    cin>>temp;
    fflush(stdin); //This will solve your problem
    
    if(i==0){
        max = temp;
    }
    
    if(temp>max){
        max = temp;
    }
    total = total   temp;
    i  ;
}
avg = total/num;
cout<<"avg"<<avg<<" "<<"max"<<max<<endl;

return 0;

I fixed the issue using fflush(stdin), this function cleans the buffer. It's recommended used it before or after of the data input, just to make shure that the buffer is clean.

Input:

3 -1 -2 -10

Output:

avg-4 max-1

This because -1 -2 -10 = -13 and -13/3 = 4.3. But you are using int so, it's going to be rounded, the result is 4

Also it works with positive values at beginning and the last one negative.

Input:

3 5 10 -1

Output:

avg4 max10
  •  Tags:  
  • c
  • Related