【问题标题】:Population growth math issue in cc中的人口增长数学问题
【发布时间】:2021-06-26 04:17:39
【问题描述】:

我已经看过了,想知道我的数学问题在哪里。我相信它应该正确计算,但浮点数不会四舍五入,0.75 到 1 以增加出生/死亡人数。我是c的新手。这是我到目前为止的代码:

float births(long popul);
float deaths(long pop);
long yearAdjustment(long pop);
int threshold(long population, long end);

int main(void){

    long begin = 0;
    long end = 0;
    int year = 0;
    float input = 0.0;

    do{
        // TODO: Prompt for start size
       input = get_float("Beginning population: ");
       begin = (long) roundf(input);
    } while (begin < 9);

    do{
        // TODO: Prompt for end size
        input = get_float("Ending population: ");
        end = (long) roundf(input);
    } while (end < begin || end <= 0);

    if(begin == end)
    {
        year = 0;
    } else
    {
        year = threshold(begin, end);
    }
    // TODO: Print number of years
    printf("Years: %i\n", year);
}

    
float births(long pop){
    float tmp = pop / 3;
    return tmp;
}

float deaths(long pop){
     float tmp = pop / 4;
     return tmp;
}

long yearAdjustment(long pop){
    long tmp = pop + ((long) roundf(births(pop) - deaths(pop)));
    return tmp;
}

int threshold(long population, long end){
    int years = 0;
    long tmp = 0;

    // TODO: Calculate number of years until we reach threshold
    while (tmp < end){
        tmp += yearAdjustment(population);
        years++;
    }
    return years;
}

我使用长整数,因为数字可能以数千开头。在出生/死亡的划分中,花车是为了更精确,更圆润。本质上,它应该分别增加大约 1/10/100... 的单个/数十/数百 ... 输入。输入 9 时为 1.25。这就是小数点很重要的地方。从技术上讲,每 4 年我会额外获得 1 次。说 18 作为结束应该是 8 年。

谢谢。

【问题讨论】:

  • float tmp = pop / 4;是整数除法,所以小数部分被舍弃了,做float tmp = pop / 4.0f;大概想做吧。
  • 感谢您指出这一点。我确实记得在其中一次讲座中说过,但我忘记了。我很喜欢布置结构,但我错过了细节。
  • long tmp = population; 然后tmp += yearAdjustment(tmp);。 CS50 标准的一部分是检查start 是否不小于9。如果是CS50项目,就不需要浮点计算了。
  • 是cs50的问题,。我正在旁听课,真的没有人可以谈论这个。其中一项检查是它处理十进制数。从检查来看,它似乎是从十进制结果的组合中寻找调整。使用 9 到 18 会导致 9 步而不是 8,这是根据 check50 输出的正确答案,尽管我得到 2。这就是为什么我意识到我的问题与数学有关,而不是我的代码。有没有更好的算法来解决这个问题?我的算法实现错了吗?
  • 我想我意识到了我的问题。我应该用人口初始化 tmp 并删除在年份调整中添加的人口。本质上,我是通过每次添加原始人口来增加原始人口,而不是调整年份,这是我唯一应该添加到原始人口的事情。

标签: c math value-iteration


【解决方案1】:

用人口初始化 tmp 并删除在年份调整中添加的人口。每次迭代都在增加人口,创造超出年度调整的增长。与平衡支票账户类似,您不会将原始余额添加到每笔交易中。

【讨论】:

    【解决方案2】:

    主要问题是您使用的是“long”,这与“long int”相同,因此它不会为您的划分提供任何精确度。 你可以改用'long double',这样它也会给你小数。

    【讨论】:

    • 谢谢。你说得对。携带小数值很重要,因此它将在多次迭代中按小数进行调整。
    猜你喜欢
    • 1970-01-01
    • 2019-09-05
    • 2021-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-11
    • 2020-07-21
    • 1970-01-01
    相关资源
    最近更新 更多