【问题标题】:Getting while loop to display让while循环显示
【发布时间】:2016-02-07 11:58:22
【问题描述】:
#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;

int main()
{
    int principal = 1000;
    int years = 1; //counter
    double balance = 0.0;
    double rate = .02; 

    do
    {
        cout << "Year " << years << ":" << endl;

        while (rate < .05)
        {
            balance = principal * pow(1 + rate, years); //display rate with no decimal place
            cout << fixed << setprecision(0);
            cout << "   Rate" << rate * 100 << "%: $";
            cout << setprecision(2) << balance << endl; //display balance with two decimal places
            rate += .01;
        }
        years += 1;
    } while (years < 6);

    system("pause");
    return 0;
}

我有这个程序,可以按 2%、3% 和 4% 计算年利率,并显示 5 年以上的金额。我的 while 循环将在第一年运行并显示它,但不是第 2 年到第 5 年。我已经多次编辑了该程序,但似乎无法让它显示结果。对此的任何帮助将不胜感激。

【问题讨论】:

    标签: c++ loops while-loop


    【解决方案1】:
    do
    {
        cout << "Year " << years << ":" << endl;
        double rate = .02;
        ^^^^^^^^^^^^^^^^^^
        while (rate < .05)
        // rest of the code...
    

    每次外循环运行时,您忘记将rater 重置回.02。因此,外部循环确实按其应有的方式执行,但由于上述错误,内部循环没有执行任何操作,因此您没有得到任何输出。

    此外,比较double 或float 的值以便在循环或条件中做出决定并不是一个好主意。由于浮点运算由于其内部表示在计算机中并不完全准确,因此您的条件可能会与您期望的相反。最好以仅比较整数或布尔类型的方式重做代码,并在其他地方执行浮点计算。

    这是关于我将如何做的(包括我不知道的@vsoftco 的修复!为了完整性和正确性,希望你不要我把它包括在这里)。 for 循环使这个更整洁:

    #include <iostream>
    #include <iomanip>
    #include <cmath>
    
    using namespace std;
    
    int main(int argc, char **argv)
    {
        const int principal = 1000;
        double balance = 0.0;
    
        for (int years = 1; years < 6; ++years)
        {
            cout << "Year " << years << ":" << endl;
            for (int ratePercent = 2; ratePercent < 5; ++ratePercent)
            {
                double rate = ratePercent / 100.0;
                balance = principal * pow(1 + rate, years);
                cout << fixed << setprecision(0);
                cout << "   Rate" << ratePercent << "%: $";
                cout << setprecision(2) << balance << endl;
            }
        }
    
        cin.get(); // <--- per vsoftco comment!
        return 0;
    }
    

    【讨论】:

    • 感谢修复!
    • 我稍微缩短了代码,见上文。它可能可以进一步缩短,但这超出了本示例的范围。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-13
    • 2012-02-22
    • 2014-07-13
    • 2013-03-07
    • 1970-01-01
    • 1970-01-01
    • 2019-09-03
    相关资源
    最近更新 更多