Nebulan
Nebulan

Reputation: 11

Calculating values from a while loop?

I need to use data entered into my while loop to calculate a sum and a max value. I'm confused as to how I can take the user input for each "day" I have stored as "weathervalue" and use it in a formula to outside the loop. Here is my code.

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

Upvotes: 0

Views: 2064

Answers (2)

CinCout
CinCout

Reputation: 9619

You do not need arrays to do this task. Two variables representing the current state would do:

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

You can also use std algorithms present in <algorithm>, but that would be just a cakewalk then!

Upvotes: 1

JDługosz
JDługosz

Reputation: 5642

I think you are asking how to store all the entered values?

Use a colle tion, such as vector.

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

Upvotes: 0

Related Questions