如何增加"for loop"呈现的结果?

How do I increase the result presented by my "for loop"?

本文关键字:结果 loop for 增加 何增加      更新时间:2023-10-16
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;
}