繁体   English   中英

如何不断更新变量的值?

[英]How do I keep updating a variable's value?

我试图编写一个代码,它会告诉我使用单位时间量(round)和人口(pop)的指数增长,但最终得到的代码是从原始变量计算值。 例如,当我输入 10000 为 pop 和 3 为 round 时,它应该首先计算 10000 的 %5,将其添加到原始值,然后再用新值再计算 2 次。 每次重复 for 循环时,我似乎都找不到更新 pop 的方法。 有人能帮我吗?

#include <iostream>

using namespace std;

int main() {
    int pop, new_people;
    int i, round;

    cout << "Population: ";
    cin >> pop;
    cout << "Round: ";
    cin >> round;

    new_people = (pop * 5) / 100;
    
    for (i = 1; i <= round; i++) {
        pop += new_people;
        cout << pop;
    }

    return 0;
}

您需要将 new_people 更新放在 for 循环中,以便每轮更新它。

#include<iostream>
using namespace std;

int main() {
int pop, new_people;
int i, round;

cout << "Population: ";
cin >> pop;
cout << "Round: ";
cin >> round;


for(i = 1; i<=round; i++){
    new_people = (pop*5)/100;
    pop += new_people;
    cout << pop;
}
return 0;
}

您可以将“new_people = (pop * 5) / 100”和“pop += new_people”放入循环中,以更新“new_people”和“pop”的值。

#include<iostream>
using namespace std;
int main() {
    int pop, new_people;
    int i, round;

    cout << "Population: ";
    cin >> pop;
    cout << "Round: ";
    cin >> round;

    for (i = 1; i <= round; i++) {
        new_people = (pop * 5) / 100;
        pop += new_people;
        cout << "round" << i << ": " << pop << endl;
    }
    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM