首页 文章

从while循环计算值?

提问于
浏览
0

我需要使用输入到while循环中的数据来计算总和和最大值 . 我很困惑我如何能够将每天存储为“weathervalue”的“day”用户输入,并将其用于公式之外的循环中 . 这是我的代码 .

#include <iostream>

using namespace std;

int main ()
{
double weatherdays;
double weathervalue;
double counter;
double day;

cout << "Enter the number of days for which you have weather data - ";
cin >> weatherdays;

counter = 1;
day = 1;

while (counter <= weatherdays)
{
    counter++;

    cout << "What is the rainfall for day " << day << endl;
    cin >> weathervalue;

    cout << "What is the max temp for day " << day << endl;
    cin >> weathervalue;

    day = day + 1;
}

weathervalue = //formula for sum of rainfall values entered in while loop

cout << "The total rainfall is " << weathervalue << endl;

weathervalue = //formula for max temp values entered in while loop

cout << "The max temperature is " << weathervalue << endl;

2 回答

  • 1

    你做 not need数组来完成这个任务 . 表示当前状态的两个变量可以:

    #include <iostream>
    
    using namespace std;
    
    int main ()
    {
        int weatherdays;
        int day = 0;
        double rainfall;
        double temperature;
    
        double sumRainfall = 0.0;
        double maxTemperature = 0.0;
    
        cout << "Enter the number of days for which you have weather data - ";
        cin >> weatherdays;
    
        while (weatherdays--)
        {
            ++day;
    
            cout << "What is the rainfall for day " << day << endl;
            cin >> rainfall;
            sumRainfall += rainfall;
    
            cout << "What is the max temp for day " << day << endl;
            cin >> temperature;
            if(temperature > maxTemperature)
            {
                maxTemperature = temperature;
            }
        }
    
        cout << "The total rainfall is " << sumRainfall << endl;
    
        cout << "The max temperature is " << maxTemperature << endl;
        return 0;
    }
    

    您也可以使用 <algorithm> 中存在的 std 算法,但那只是一个小蛋糕!

  • 0

    我想你问的是如何存储所有输入的值?

    使用收集,例如 vector .

    cin >> wearhervalue;
    vals.push_back (weathervalue);
    

相关问题