Finding the largest smallest and average on the numbers you put in

Hi everyone,
I got this assingment " Develop a C++ program that detects and prints out on screen the largest, smallest and average value from a set of floating-point values entered at the keyboard. " I tried my best and got stuck. I do not know where to put the formula so I can get the right answer. please help !!



#include <iostream>
using namespace std;

int main()
{
double test, largest, smallest, average;
double sum = 0 ;
int testCounter = 0;
char another = 'y';


cout << " Enter a number : " << endl;
while ( !( cin >> test) )
{
cout << " Invalid value, re-enter the number : " << endl;
fflush(stdin);
cin.clear();
}

largest = test;
smallest = test;


while ( test != 'ii' )
{

cout << "Want another number ? 'y' or 'n' ? " << endl;
cin >> another;
while ( (another != 'y') && (another != 'n'))
{
cout << "Wrong value ! 'y' for another number and 'n' to show the result " << endl;
cin >> another;

fflush(stdin);
}
if ( another == 'y' )
{
cout << "Enter the number "<< endl;
while ( !(cin >> test)) // phai value gia tri nay , 1 while
{
cout << "Wrong value ! Re-enter the number " << endl;
cin >> test;

fflush(stdin);
}
}



if (test > largest )
{
largest = test;
}
else if (test < smallest)
{
smallest = test;
}

testCounter++;
sum = (test + sum);
average = sum/testCounter;

if ( another == 'n' )
{
cout << " you enter " << testCounter << " numbers " << endl;
cout << " Average is " << average << endl;

cout << " largest number is " << largest << endl;
cout << " smallest number is " << smallest << endl;

}


cin.clear();
fflush(stdin);

}
system ("pause");

}

// while ( ( another != 'y') && ( another != 'n' ))
//{ cout << "invalid input " << endl;
// cin.clear();
// fflush(stdin);
// cout << " another number ( y/n) ";
// cin >> another;
//}
Last edited on
Your code is messy and you're not using [code] tags, so I didn't look much into it. One mistake I noticed though is while( test != 'ii' ). test is a double, 'ii' is a char (god knows what it's value is. string would be "ii"). Comparing them makes no sense.

Your code should be
1
2
3
4
5
6
7
8
9
10
11
12
13
while(true){
   if( cin >> double_input ){
      sum += double_input;
      count++;
      if(count == 0 || double_input < lowest) lowest = double_input;
      if(count == 0 || double_input > highest) highest = double_input;
   }else{
      cin.clear();
      cin >> string_input;
      if(string_input == "exit") break;
      else cout << string_input << " is not a number!\n";
   }
}

or something..
Last edited on
Thank you hamsterman. I got it :D
Topic archived. No new replies allowed.