首页 > 解决方案 > 如何将计算存储在for循环中,因此每次计算时都会更新一个整数值并稍后打印出来,C

问题描述

我的目标的详细信息:假设我们有 n 只美洲驼。每年,n / 3 只新美洲驼出生,n / 4 只美洲驼去世。

例如,如果我们从 n = 1200 只美洲驼开始,那么在第一年,将会有 1200 / 3 = 400 只新的美洲驼出生,而 1200 / 4 = 300 只美洲驼会死去。在那年年底,我们将有 1200 + 400 - 300 = 1300 只美洲驼。

我得出的结论是,每 1200 / 3 和 1200 / 4 一年过去,现在我正在尝试使用 for 循环来迭代一个变量,每次计算完成时,它都会迭代 + 1 意味着它算作一个年已经过去,然后打印出过去的年数。

预期结果:
./population
开始大小:100
结束大小:1000000
年:115

这是我到目前为止所尝试的。我相信这段代码中的一切都是正确的,除了 for 循环,我无法得到应该如何进行计算然后打印出来的逻辑。我总是以零结束一年。

这是代码:

#include <cs50.h>
#include <stdio.h>

int main(void)
{
    int start_pop_size;
    int end_pop_size;
    int years_passed;


    // TODO: Prompt for start size

        do
        {
          start_pop_size = get_int ("Enter starting population size: \n");
        }
        while (start_pop_size < 9);

    // TODO: Prompt for end size
        do
        {
            end_pop_size = get_int ("Enter ending population size: \n");
        }
        while (end_pop_size <= start_pop_size);

    // TODO: Calculate number of years
    for(years_passed = 0; years_passed < start_pop_size / 3 - end_pop_size / 4; years_passed++)
    {
        int calculation = start_pop_size / 3 - end_pop_size / 4;
    }

     // TODO: Print number of years

    printf("Years : %i", years_passed);
}

标签: cfor-loopcs50

解决方案


您事先不知道达到 需要多少次迭代end_pop_size,因此您的条件不能基于years_passed。相反,您需要跟踪当前人口并根据此决定何时结束循环:

int cur_pop_size = start_pop_size;
years_passed = 0;
do {
    // calculation goes here
    years_passed++;
while (cur_pop_size < end_pop_size);

您也可以将其表示为 a for,但再次注意条件是关于 thecur_pop_size而不是关于 the years_passed

int cur_pop_size = start_pop_size;
for (years_passed = 0; cur_pop_size < end_pop_size; years_passed++) {
    // calculation goes here
}

推荐阅读