正在计算while循环中的值

Calculating values from a while loop?

本文关键字:循环 while 计算      更新时间:2023-10-16

我需要使用输入while循环的数据来计算和和和最大值。我很困惑如何将我存储为"weathervalue"的每个"天"的用户输入作为"weathervalue",并在循环之外的公式中使用它。这是我的密码。

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

您不需要数组来完成此任务。表示当前状态的两个变量可以:

#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算法,但那只是小菜一碟!

我想您在问如何存储所有输入的值?

使用集合,例如vector

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