使用while循环c ++从文件中提取最小值

Extracting the minimum value from a file using a while loop c++

我需要在声明中将最小值 (minValue) 设置为 -1。我如何使用 || (或条件)在我的 while 循环中,考虑到负值结束程序,从一组正数中提取最小值?此外,双平均值变量(平均值)并未计算预期值。例如,如果该值应为 35.7789,则为 returning 35.0000。我还打算在不需要时将平均值设为 return,不带小数点。例如,如果用户首先输入负值,则平均值应为 0 而不是 0.0000。我该如何操纵平均变量才能做到这一点?

#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.

初始化为-1,所有正数都将大于minValue

你可以set/initialize用最大值或第一个输入值,或者在循环中处理特殊情况:

if (minValue == -1 || intVal < minValue)
    minValue = intVal;

Also, the double average variable (average), is not calculating the intended value.

你的平均值是整数运算,你必须在计算过程中使用浮点数:

average = static_cast<double>(sum) / count;

the average value should be 0 as opposed to 0.0000

删除对 std::setprecision(4);

的调用