c++中重复结构中的for语句替换为while语句

Replacing a for statement with a while statement in a repetition structure in C++

本文关键字:语句 替换 while for 结构 c++      更新时间:2023-10-16

我是新来的,想在学校的一些工作上得到帮助。我需要编写以下代码:

do    //begin loop
{
     cout << "Year " << years << ":" << endl;
     for (double rate = .02; rate < .05; rate += .01)
     {
          balance = principal * pow(1 + rate, years);
          //Display rate with zero decimal places
          cout << fixed << set precision(0);
          cout << "   Rate " << rate * 100 << "%: $";
          //Display balance with two decimal places
          cout << setprecision(2) << balance << endl;
     }    //End for
     //Update years counter
     years += 1;
}    while (years < 6);

从for语句变为while语句。我有一些问题,希望我能得到一些见解,如何正确地做到这一点。谢谢你!

首先需要理解for循环的作用:

double rate = 0.2 // initialization
rate < .05 // condition and
rate += .01 // the afterthought.

所以一开始你设置你的利率变量一次,然后你检查利率是否小于0.05,在下一个循环之前你将利率增加0.01。

你可以在while循环中做同样的事情,如果你在循环前添加:

double rate = 0.2 

,在循环的末尾添加:

rate += .01