2015-10-14 84 views
0

我在这里是新来的,并试图获得有关学校工作的帮助。我需要这样的代码:在C++的重复结构中用while语句替换for语句

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语句。我遇到了一些问题,希望能够对如何正确执行此操作有所了解。谢谢!

+0

什么特别的问题?你尝试了什么? –

+1

你能解释/显示你试过的例子吗?请阅读此处,了解如何提出作业问题以及应该包括哪些内容以确保您能够得到答案,而不仅仅是低调和忽略:) http://meta.stackexchange.com/questions/10811/how-do-i -ask-and-answer-homework-questions – Sk93

+0

你知道'for'语句有3个部分吗?你有没有发现他们? while语句只有一个表达式,你应该知道'for'循环的三个部分中的哪一个对应于这个表达式。 – MSalters

回答

0

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

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

所以刚开始你设置你的速度变一次,然后要检查,如果速度你ingrement下一循环之前小于0.05和率.01。

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

double rate = 0.2 

,并在循环的末尾添加:

rate += .01