gpt4 book ai didi

C 程序 - 使用提供的方程计​​算并显示每年的人口

转载 作者:行者123 更新时间:2023-11-30 17:31:40 24 4
gpt4 key购买 nike

这是我已经完成的代码,但由于某些原因,我仍然无法弄清楚为什么。它将正确显示第 0 年的适当人口,但对于第 1 年,它将采用前一年的人口值并乘以比率,而不是使用我在代码中使用的提供的方程公式为 NextYr = 速率 * CurrentYr * (1-(CurrentYr/1000000))

任何帮助将不胜感激!

例如,

Enter the initial egret population: 12
Enter the rate: 2

Year Population
0 12
1 24
2 48
3 96
and so on
<小时/>
#include<stdio.h>
int main()
{
int count=1,year_num;
float Rate;
unsigned long CurrentYr;
unsigned long NextYr;

while (count<=1)
{
printf("Enter the initial egret population: ");
scanf("%d",&CurrentYr);
printf("Enter the rate: ");
scanf("%f",&Rate);

printf("Year Population\n");
printf("---- ----------\n");



if ((CurrentYr>0 && CurrentYr<1000000) && (Rate>0 && Rate<4))
{
NextYr = CurrentYr;
for(year_num=0;year_num<=25;year_num++)
{
NextYr = Rate * NextYr * (1-NextYr/1000000);
printf("%4d%12d\n",year_num,NextYr);

}
break;
}

else if ((CurrentYr < 0 || CurrentYr > 1000000) || (Rate<0 || Rate>4))
{
printf("Invalid Input!");
printf("Enter the initial egret population: ");
scanf("%d",&CurrentYr);
printf("Enter the rate: ");
scanf("%f",&Rate);
if ((CurrentYr>0 && CurrentYr<1000000) && (Rate>0 && Rate<4))
{
NextYr = CurrentYr;

for(year_num=0;year_num<=25;year_num++)
{
printf("%4d%12d\n",year_num,NextYr);
NextYr = Rate * NextYr * (1-NextYr/1000000);


}
break;

}
else
{
printf("No more chance ! Bye ! ");
}
}
return 0;
}
}

最佳答案

这是从您的代码复制的公式:

        NextYr = Rate * NextYr * (1-NextYr/1000000);

因此,如果 Rate 为 2,NextYr 为 12,您认为这会是:

Rate * NextYr * (1-NextYr/1000000);

由于 NextYr 是一个整数,NextYr/1000000 将为 0,所以我们剩下

2 * 12 * (1 - 0)

事实上,您的程序打印了 24 作为第 2 年的值。您为什么认为这是不正确的输出?

也许您应该尝试使用更多数量的白鹭(接近一百万)。另外,您可能不想使用整数算术来执行 NextYr/1000000 ,只要 NextYr 小于一百万,整数算术就会始终向下舍入为 0。尝试类似 NextYr/1000000.0 的内容;通过将其中一个值设为浮点,您将导致除法成为浮点。不过,我可能会写 ((float)NextYr)/1000000.0 只是为了更加清楚我们想要什么。

您也可以尝试接近 1 的速率。

关于C 程序 - 使用提供的方程计​​算并显示每年的人口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24501643/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com