I am required to set the minimum value (minValue) equal to -1 in my declarations. How do I, using the || (or condition) within my while loop, extract a minimum value from a positive set of numbers considering that a negative value concludes the program? Also, the double average variable (average), is not calculating the intended value. For example, if the value is supposed to be 35.7789, it is returning 35.0000. I am also intending for the average value to return with no decimal point when unnecessary. For example, if the user enters a negative value first, the average value should be 0 as opposed to 0.0000. How do I manipulate the average variable in order to do so?
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int intVal;
int sum = 0;
int maxValue = -1;
int minValue = -1;
double average = static_cast<double>(0);
int count = 0;
int evenCount = 0;
int oddCount = 0;
cout << endl << "Enter an integer (negative value to Quit): ";
cin >> intVal;
cout << endl;
while(intVal >= 0)
{
if(intVal > maxValue)
maxValue = intVal;
if(intVal < minValue)
minValue = intVal;
count ++;
sum += intVal;
if(intVal > 0)
average = sum / count;
if(intVal % 2 == 0)
evenCount ++;
else
oddCount ++;
cout << "Enter an integer (negative value to Quit): ";
cin >> intVal;
cout << endl;
}
cout << fixed << setprecision(4);
cout << "Values entered:" << setw(8) << right << count << endl;
cout << "Sum of numbers:" << setw(8) << right << sum << endl;
cout << " Average value:" << setw(8) << right << average << endl;
cout << " Maximum value:" << setw(8) << right << maxValue << endl;
cout << " Minimum value:" << setw(8) << right << minValue << endl;
cout << " Even numbers:" << setw(8) << right << evenCount << endl;
cout << " Odd numbers:" << setw(8) << right << oddCount << endl;
cout << endl;
}
I am required to set the minimum value (minValue) equal to -1 in my declarations.
With initialization to -1
, all positive numbers will be greater than minValue
.
You can set/initialize it with max value or first input value, or handling the special case in the loop:
if (minValue == -1 || intVal < minValue)
minValue = intVal;
Also, the double average variable (average), is not calculating the intended value.
Your average does integer arithmetic, you have to use floating point during the computation:
average = static_cast<double>(sum) / count;
the average value should be 0 as opposed to 0.0000
Remove the call to std::setprecision(4);