C 程序不显示任何输出,但它接受来自 CS50 Lab1 的输入问题

问题描述 投票:0回答:2

假设我们有 n 只美洲驼。每年,n / 3 只新美洲驼出生,n / 4 只美洲驼去世。

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

#include <math.h>
#include <stdio.h>

int main(void)
{
    // TODO: Prompt for start size
    int a, b;
    do
    {
        printf("Start Size: ");
        scanf("%i", &a);
    }
    while (a < 9);
    // TODO: Prompt for end size
    do
    {
        printf("End Size: ");
        scanf("%i", &b);
    }
    while (b < a);
    // TODO: Calculate number of years until we reach threshold
    int y = 0;
    while (a < b)
    {
        a = round((float)a + (a / 4) - (a / 3));
        y++;
    }

    // TODO: Print number of years
    printf("Years: %i\n", y);
}

我尝试的输入和我期望的输出:

  1. 起始尺寸:1200
    最终尺寸:1300
    年数:1

  2. 起始尺寸:-5
    起始尺寸:3
    起始尺寸:9
    末端尺寸:5
    最终尺寸:18
    年龄:8

  3. 起始尺寸:20
    末端尺寸:1
    最终尺寸:10
    最终尺寸:100
    年龄:20

  4. 起始尺寸:100
    最终尺寸:1000000
    年龄:115

c cs50
2个回答
0
投票

while 循环中有一个拼写错误

a = round((float)a + (a / 4) - (a / 3));

看来你的意思是

a = round((float)a - (a / 4) + (a / 3));

还将变量

a
转换为 float 没有意义。相反,你可以写例如

a = round(a - (a / 4.0) + (a / 3.0));

0
投票

公式不正确:你交换了新生美洲驼的数量和已故美洲驼的数量。

写这个吧

a = round((float)a + (a / 3) - (a / 4));

请注意,您应该使用普通整数算术:

a = a + a / 3 - a / 4;
© www.soinside.com 2019 - 2024. All rights reserved.