dannyelloko20 dannyelloko20 - 1 month ago 4
C++ Question

For loop with different inputs

please see my code below and let me know what I'm not seeing. I've tried almost everything to make it work and nothing yet.

Thanks in advance for your time and help.

for (double c = c1; c <= c2; c = c + i)
{
cout << "Enter the lowest temperature: " << endl;
cin >> c1;
cout << "Enter the highest temperature: " << endl;
cin >> c2;
cout << "Enter the desired increment in temperature: " << endl;
cin >> i;

f = ((9 / 5) * c) + 32;

cout << "When C is " << c << " degrees Celsius, the temperature in Fahrenheit will be: " << f << " degrees." << endl;

cin.get();
}
return 0;


}

Answer

You take the input in the wrong part of the code.

c1 and c2 were probably never assigned before the loop, and your logic as reflected in the codedoesn't seem to match your intentions as it changes the loop limit every time.

Also, note using 9.0 instead of 9 to get a double result and not an integer.

See full example here https://ideone.com/Uj974z.

int main() {

    double c1, c2, i, f;

    cout << "Enter the lowest temperature: " << endl;
    cin >> c1;
    cout << "Enter the highest temperature: " << endl;
    cin >> c2;
    cout << "Enter the desired increment in temperature: " << endl;
    cin >> i;

    for (double c = c1; c <= c2; c = c + i)
    {
        f = ((9.0 / 5) * c) + 32;
        cout << "When C is " << c << " degrees Celsius, the temperature in Fahrenheit will be: " << f << " degrees." << endl;
    }

    return 0;
}
Comments