Home > Net >  This code that is supposed to get the largest and average of input numbers is not giving me the desi
This code that is supposed to get the largest and average of input numbers is not giving me the desi

Time:09-15

I've been trying to get this code to give me an output of "20 9.50" when I input "15 20 0 3 -1" but it keeps giving me the output "20 0.55". This is the code I've made:

#include <iostream>
#include <iomanip>
using namespace std;

int main() {

   int largest = 0;
   int number = 0;
   int count = 0;
   double avg = 0;
   
   while (number >= 0) {
      cin >> number;
      if (number >= 0) {
         if (number > largest) {
            largest = number;
         }
         avg  = number;   count;
      }
      if (count > 0) {
         avg /= count;
      }
   }
   cout << largest << " " << fixed << setprecision(2) << avg << endl;

   return 0;
}

Can anyone point out how I'm getting the wrong output? I'm in a class for C but I'm still new to it. Hopefully I'm not treated too harshly, any help is appreciated.

CodePudding user response:

I am not sure if you are supposed to maintain the average "on the fly".

The better, less error-prone, approach is to maintain a total for the life of the loop. Then, after the while loop, you should average by dividing the total by the count.

FYI, for everyone else: The -1 ends the while loop and total & count should not include the -1 at the ending of every input.

The following code gives output of 20 9.50 with input of 15 20 0 3 -1.

#include <iostream>
#include <iomanip>
using namespace std;

int main() {

   int largest = 0;
   int number = 0;
   int count = 0;
   double avg = 0;
   double total = 0;

   while (number >= 0) {
      cin >> number;
      if (number >= 0) {
         if (number > largest) {
            largest = number;
         }
         //avg  = number;   count;
         total  = number;   count;
      }
      //if (count > 0) {
      //   avg /= count;
   }
   
   avg = total / count;
   cout << largest << " " << fixed << setprecision(2) << avg << endl;

   return 0;
}

CodePudding user response:

You divide avg by count several times. But you must do it one more after cycle

#include <iostream>
#include <iomanip>
using namespace std;

int main() {

    int largest = 0;
    int number = 0;
    int count = 0;
    double avg = 0;

    while (number >= 0) {
        cin >> number;
        if (number >= 0) {
            if (number > largest) {
                largest = number;
            }
            avg  = number;   count;
        }
        
    }
    if (count > 0) {
        avg /= count;
    }
    cout << largest << " " << fixed << setprecision(2) << avg << endl;

    return 0;
}
  •  Tags:  
  • c
  • Related