簡體   English   中英

使用 while 循環從文件中提取最小值 c++

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

我需要在聲明中將最小值 (minValue) 設置為 -1。 我該如何使用 || (或條件)在我的while循環中,考慮到負值結束程序,從一組正數中提取最小值? 此外,雙平均變量(平均值)並未計算預期值。 例如,如果該值應為 35.7789,則返回 35.0000。 我還打算在不必要時返回不帶小數點的平均值。 例如,如果用戶首先輸入負值,則平均值應為 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;
        
}

我需要在聲明中將最小值 (minValue) 設置為 -1。

初始化為-1時,所有正數都將大於minValue

您可以使用最大值或第一個輸入值設置/初始化它,或者在循環中處理特殊情況:

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

此外,雙平均變量(平均值)並未計算預期值。

你的平均值是 integer 算術,你必須在計算過程中使用浮點數:

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

平均值應為 0 而不是 0.0000

刪除對std::setprecision(4);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM