c++中重复结构中的for语句替换为while语句
Replacing a for statement with a while statement in a repetition structure in 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语句。我有一些问题,希望我能得到一些见解,如何正确地做到这一点。谢谢你!
首先需要理解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
相关文章:
- 模板参数替换失败,并且未完成隐式转换
- 我的简单if-else语句是如何无法访问的代码
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 如何用转义符替换字符串中的所有特殊字符
- 线程,如果else语句,都是错误的上下文切换后,会发生什么
- 为什么是0;C++中的有效语句
- Insert函数不适用于2 if语句C++
- If语句未被求值C++
- 什么可以用来替换代码中的循环和 if 语句?
- 有没有更有效的方法来替换这些多个 IF 语句?
- 在文件中搜索 printf 语句并替换为字符串值
- C++:将'this'指针与"get"函数一起使用以替换 cout 语句的可能性
- 如何用逐位操作替换此if/else语句
- C++break语句替换
- 替换goto语句
- 用无分支代码替换if-else语句
- c++中重复结构中的for语句替换为while语句
- 我如何用等价的结构化语句替换continue和goto语句
- 在模板化代码和非模板化代码之间进行接口时替换switch语句
- sql语句插入或替换从java到c++ NDK Android