对于具有不同输入的循环

时间:2016-10-30 23:32:06

标签: c++ for-loop

请参阅下面的代码,让我知道我没有看到的内容。我已经尝试了几乎所有的东西,以使它工作,但没有。

提前感谢您的时间和帮助。

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;

}

2 个答案:

答案 0 :(得分:2)

您在输入错误的代码部分。

c1c2可能从未在循环之前分配过,而且您在编码中反映的逻辑似乎与您的意图相符,因为它每次都会更改循环限制。

另请注意,使用9.0代替9来获取double结果,而不是整数。

请参阅此处的完整示例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;
}

答案 1 :(得分:0)

问题是9/5返回1.你应该写9.0 / 5。