【问题标题】:How to make the output `1` when the input is "1200" and "1300"?当输入为“1200”和“1300”时,如何使输出为“1”?
【发布时间】:2021-09-12 22:50:44
【问题描述】:

运行此代码并将startn 输入1200 并将endn 输入1300 时,输出为Years:0。在哪里通过给定的测试应该是Years:1。请注意,代码运行时不会出错,并且可以与其他数字一起使用。

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



int main(void)
{
    int startn;
    int endn;

    do
    {
    startn = get_int("what should the starting number of llamas be?\n");
    endn = get_int("what should the ending number of llamas be?\n");
    }
    while (startn < 9 || endn < startn);


    float total = (startn + startn/3 - startn/4);
    float finalTotal = total;
    int n=0;
    
    
    while (finalTotal<endn)
    {
        finalTotal = (finalTotal + finalTotal/3 - finalTotal/4);
        n++;
    }


    printf("Years: %i\n", n);
}

代码的目的是计算到达给定的骆驼最终种群endn 所需的年数,并从给定的骆驼种群开始。在这样做的同时,我们添加了出生的美洲驼+ finalTotal/3 并删除了死亡的美洲驼- finalTotal/4。然后将总数保存在finalTotal

【问题讨论】:

  • 代码应该做什么?您给我们举了一个例子,但没有告诉我们总体要求。
  • 我会编辑的。
  • 高度可疑:依赖float 精确到整数级别。使用在int(将截断)和float(不会)上运行的除法具有相同的代码。
  • 你有什么建议?
  • start 1200 和 end 1301 的答案应该是什么?

标签: c integer cs50


【解决方案1】:

如果你用startn 初始化finalTotal,那么它将起作用。您的代码如下所示:

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



int main(void)
{
    int startn;
    int endn;

    do
    {
    startn = get_int("what should the starting number of llamas be?\n");
    endn = get_int("what should the ending number of llamas be?\n");
    }
    while (startn < 9 || endn < startn);

    float finalTotal = startn;
    int n=0;

    while (finalTotal<endn)
    {
        finalTotal = finalTotal + (int)(finalTotal/3) - (int)(finalTotal/4);
        n++;
    }

    printf("Years: %i\n", n);
}

您手动计算了第一年,因此它从未进入最后一个 while

此外,您也应该将美洲驼视为整数,而不是浮点数。 经过一点重构和更合适的变量名称后,代码如下所示:

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


int main(void)
{
    int start_num;
    int end_num;

    do
    {
        start_num = get_int("what should the starting number of llamas be?\n");
        end_num = get_int("what should the ending number of llamas be?\n");
    }
    while (start_num < 9 || end_num < start_num);

    int current_num = start_num;
    int years = 0;

    while (current_num < end_num)
    {
        int new_borns = current_num / 3;
        int deaths = current_num / 4;
        current_num = current_num + new_borns - deaths;
        years++;
    }

    printf("Years: %i\n", years);
}

【讨论】:

  • 喜欢你的代码。但是您手动计算了第一年的进度,仍然将n 初始化为0,就像什么都没发生一样。如果您从代码中删除该部分,只需从 startn 开始并将 n 设置为 0 即可正常工作
  • 出现了一个新问题...因为起始数字是“100”,所以输出是 116,而应该是 115
  • double代替float,更精确。
  • 使用double时同样的问题。
  • 新案例的endn是什么?
猜你喜欢
  • 2020-11-04
  • 2014-06-21
  • 1970-01-01
  • 2019-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多