如何增加"for loop"呈现的结果?
How do I increase the result presented by my "for loop"?
for (int j=1; j<=120; j++){
Pop=10180000; //Pop = Population //
Increase=Pop*0.0118;
Pop=Increase+Pop;
cout<< Increase <<endl;
cout<< Pop <<endl;
}
我在这里真的很新,如果我犯了错误,对不起。我假设找出 120 个月的人口数量 (10.18mil(,每月增加 1.18%。
我设法找到了第一个月,但我的 for 循环在接下来的 120 行中每行都重复相同的结果。
您的问题是您在循环的每次迭代中都设置了总体的初始值。您应该在循环开始之前执行此操作一次。
您还可以简化计算,因为只需乘以 1.18% 即可实现1.0118
.这给你的东西如下:
int Pop = 10180000;
for (int i = 1; i <= 120; i++)
Pop = Pop * 1.0118;
cout << Pop << endl;
当然,如果您正在编写实际代码,则可能需要分解功能,以便可以轻松重用它:
int increaseValue(
int value,
double ratePerPeriod,
unsigned int periodCount
) {
for (unsigned int i = 0; i < periodCount; i++)
value *= (ratePerPeriod / 100.0 + 1.0);
return value;
}
:
cout << increaseValue(10180000, 1.18, 120) << endl;
在代码中,在每次迭代开始时将Pop
重新初始化为 10180000。您应该将其移动到循环上方,以便其值不会在每次迭代时重置。
Pop=10180000; //Pop = Population //
for (int j = 1; j <= 120; j++) {
Increase=Pop*0.0118;
Pop=Increase+Pop;
cout<< Increase <<endl;
cout<< Pop <<endl;
}
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- valgrind-hellgrind与泄漏检查的结果不同
- 用C++20 fmt限制结果的总大小
- 如何返回一个类的两个对象相加的结果
- 为什么我不能在 FOR LOOP 中使用 i/10,C++?
- Arduino:for/while/if在void setup()或void loop()之前?——错误:之前需要不合格
- 使用QProcess执行命令,并将结果存储在QStringList中
- 如果我std::dynamic_pointer_cast并且底层dynamic_cast的结果为null,那么返回的sh
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- 序列化,没有库的整数,得到奇怪的结果
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 在更改for循环的第三部分后,未使用for循环结果
- 使用++运算符会导致意外的结果
- 为什么在逗号分隔符上下文中将预增量的结果强制转换为void
- C++Brute Force攻击函数不会返回结果
- 你好。。。id_public变量不应该给出结果为 81 和 86 吗?为什么它为两个派生类占用不同的内存位置?
- 算术运算的结果类似于:C浮点变量中的1/3
- ";结果类型必须是可从输入范围的值类型""构造的;创建std::vector时
- 密码登录程序将永远循环并显示不正确的结果
- 如何增加"for loop"呈现的结果?