C语言程序的试验问题,经典猴子吃桃问题,为什么我所写的代码不能得出正确的值?求大神指导。

2025-05-08 16:59:43
推荐回答(2个)
回答1:

你这个写法有问题
#include
int a, b =0, sum=0, days;
int cal(int);
int main()
{
printf("Please enter the max number:");
scanf("%d", &days);
sum = cal(days);
printf("The sum of these peaches are:%d\n", sum);
}
int cal(int x)
{
for (a = 0; a < x; a++)
{
b= (b+1)* 2;
printf("第%d天吃%d桃子\n",a+1,b);
}
return b;
}

回答2:

#include
int a, b = 1, sum, days;
int cal(int);
int main()
{

printf("Please enter the max number:");
scanf("%d", &days);

sum = cal(days);
    printf("The sum of these peaches are:%d\n", sum);
return 0;
}
int cal(int x)
{
for (a = 1; a {
sum = (sum + 1) * 2;

}
return sum;
}