Friday, July 31, 2009

Finding the Max, Min, Mean, C++ without using arrays?

My mean is not working correctly and I was told I could not use arrays to find the minimum, maximum or mean of the values inputted. Help please on the following code?


-Thanks





#include %26lt;iostream%26gt;


using namespace std;





int main( )


{


double numbers[999];


double amountNumbers;


double maximum;


double minimum;


int i = 0;


double mean = 0;





cout %26lt;%26lt; "How many numbers will be entered?\n";


cin %26gt;%26gt; amountNumbers;





cout %26lt;%26lt; "Seperate your numbers by pressing RETURN after every input:\n";


cin %26gt;%26gt; numbers[0];





minimum = maximum = numbers[0];


for(i=1; i%26lt;amountNumbers; i++)


{


cin %26gt;%26gt; numbers[i];





if(numbers[i] %26lt; minimum)


minimum = numbers[i];


if(numbers[i] %26gt; maximum)


maximum = numbers[i];





mean = mean + numbers[i];


}





mean = mean / amountNumbers;





cout.setf(ios::fixed);


cout.setf(ios::showpoint);


cout.precision(3);


cout%26lt;%26lt; "Minimum: "%26lt;%26lt; minimum %26lt;%26lt; "\n"


%26lt;%26lt; "Maximum: "%26lt;%26lt; maximum %26lt;%26lt; "\n"


%26lt;%26lt; "Mean: " %26lt;%26lt; mean %26lt;%26lt; "\n";





return 0;


}

Finding the Max, Min, Mean, C++ without using arrays?
Two errors in there.


First you do use arrays: double numbers[999] is an array


Second, your loop should start with 0 not one or start with one and compare using %26lt;= amountNumbers. In any case it should run amountNumber of time.





See this working example


int main( )


{


double sum = 0.0;


unsigned int amountNumbers = 0;


double maximum = 0.0;


double minimum = 0.0;


double mean = 0.0;





cout %26lt;%26lt; "How many numbers will be entered?\n";


cin %26gt;%26gt; amountNumbers;





cout %26lt;%26lt; "Seperate your numbers by pressing RETURN after every input:\n";


for (unsigned int i=0; i%26lt;amountNumbers; i++)


{


double currentValue = 0.0;


cin %26gt;%26gt; currentValue;





if (currentValue %26lt; minimum)


minimum = currentValue;





if (currentValue %26gt; maximum)


maximum = currentValue;





sum = sum + currentValue;


}





mean = sum / amountNumbers;





cout.setf(ios::fixed);


cout.setf(ios::showpoint);


cout.precision(3);


cout%26lt;%26lt; "Minimum: "%26lt;%26lt; minimum %26lt;%26lt; "\n"


%26lt;%26lt; "Maximum: "%26lt;%26lt; maximum %26lt;%26lt; "\n"


%26lt;%26lt; "Mean: " %26lt;%26lt; mean %26lt;%26lt; "\n";





return 0;


}
Reply:I see the problem. Start your for loop from 0 instead of 1, otherwise if you are checking N results, you are actually checking N-1 if you start from 1. Or you could do:





for (i = 1; i %26lt;= amountNumbers; i++)


...


No comments:

Post a Comment