【问题标题】:Why doesn't this while loop show the first element?为什么这个while循环不显示第一个元素?
【发布时间】:2017-09-18 05:06:21
【问题描述】:

我是 C++ 初学者,想做this 练习。以下是我的代码,但我不知道为什么在 cout 循环时它不显示下限。

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    double low=-0.000001, high=-0.000001, step=0.0, stop, f;
    while (low <= -0.000001 || low > 50000) {
        cout << "Lower limit (0~50,000): "; cin >> low;
        if (low <= -0.000001) {cout << "Must be positive." << endl;}
        else if (low > 50000) {cout << "Out of range." << endl;}
    }
    while (high <= -0.000001 || high > 50000 || high <= low) {
        cout << "Higher limit (0~50,000): "; cin >> high;
        if (high <= -0.000001) {cout << "Must be positive." << endl;}
        else if (high > 50000) {cout << "Out of range." << endl;}
        else if (high <= low) {cout << "Must higher than lower limit." << endl;}
    }
    while (step <= 0 || step > high) {
        cout << "Step (0.000001~" << high << "): "; cin >> step;
        if (step <= 0) {cout << "Must be positive." << endl;}
        else if (step > high) {cout << "Out of range." << endl;}
    }
    cout << endl << "Celsius\t\tFahrenheit" << endl;
    cout << "-------\t\t----------" << endl;
    stop = low;
    while (stop < high) {
        f = 1.8 * stop + 32.0;
        stop += step;
        cout << fixed << setprecision(6) << stop << "\t" << fixed << setprecision(6) << f << endl;
    }
    return 0;
}

例如,如果我输入 1.5 作为下限,我想它的输出应该以 1.5 开头,但它以 2.0 开头...我该如何解决这个问题?谢谢。

Img of Not the outcome I want

【问题讨论】:

    标签: c++ while-loop converter temperature


    【解决方案1】:

    stop 第一次被打印是在第一个增量之后:

    while (stop < high) {
        f = 1.8 * stop + 32.0;
        stop += step;                              <- increment
        cout << ... << stop << ... << f << endl;   <- print
    }
    

    将打印移到上面,它应该可以正常工作。


    旁注:使用调试器和重复的“跨步”命令很容易发现此类问题(可能需要观察一些观察值,以显示您感兴趣的值如何随时间变化)。循序渐进地执行程序会很有启发性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-03
      • 2018-03-17
      • 2016-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-12
      相关资源
      最近更新 更多