从while循环计算值?

时间:2014-10-15 07:11:49

标签: c++ while-loop

我需要使用输入到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 个答案:

答案 0 :(得分:1)

需要数组来执行此任务。表示当前状态的两个变量可以:

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

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

答案 1 :(得分:0)

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

使用收藏夹,例如vector

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