用C ++中的重复结构替换带有while语句的for语句

时间:2015-10-14 07:35:04

标签: c++

我是新来的,并试图帮助学校的一些工作。我需要制作这段代码:

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语句。我遇到了一些问题,希望能够对如何正确地做到这一点有所了解。谢谢!

1 个答案:

答案 0 :(得分:0)

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

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

所以首先你要设置你的利率变量一次,然后检查利率是否小于.05,然后在下一次循环之前你的生活费率是.01。

如果在循环之前添加,你可以使用while循环执行相同的操作:

double rate = 0.2 

并在循环结束时添加:

rate += .01