Hengrui 发表于 2023-10-30 22:30:35

count为啥不循环了

#include<stdio.h>
int main()
{
    int a=10000;
    double c;
    c=a*0.1;
    printf("小甲鱼的利息为%.2f",c);
    int count=1;
long long int g=10000+c;
long long int f=10000+10000*0.05;

    do
    {g=g+c;
    f=10000+f*0.05;
    count=count+1;}
    while(g<f);
    printf("%d",count);
   
   
    return 0;
}
为什么count只循环了一次,该咋改才能让count循环
    这是带你学c带你飞的课后作业的拾遗的课后题

isdkz 发表于 2023-10-30 22:31:21

在给定的代码中,count只循环了一次是因为循环条件(g < f)在第一次循环后就不再满足,导致循环终止。

要让count循环,你需要修改循环条件。根据你的需求,你可能希望循环继续直到g大于等于f 。所以你可以将循环条件改为(g <= f) 。

修改后的代码如下:

#include <stdio.h>

int main()
{
    int a = 10000;
    double c;
    c = a * 0.1;
    printf("小甲鱼的利息为%.2f\n", c);

    int count = 1;
    long long int g = 10000 + c;
    long long int f = 10000 + 10000 * 0.05;

    do
    {
      g = g + c;
      f = 10000 + f * 0.05;
      count = count + 1;
    }
    while (g <= f);

    printf("%d\n", count);

    return 0;
}


现在,count将会根据你的需求循环多次,直到g大于等于f 。

Mike_python小 发表于 2023-10-30 22:32:47

问题描述:
在给定的代码中,为什么count只循环了一次?如何修改代码以使count可以正确循环?

回答:
在给定的代码中,count只循环了一次的原因是使用了错误的循环条件。当前的循环条件是g < f,但实际上这会导致循环在第一次迭代后终止,因为在每次循环中,g的值会增加c的大小,而f的值只会按照固定的公式进行增加。

要使count正确循环,我们应该将循环条件修改为g <= f,即当g的值小于或等于f时继续循环。这样,count将在满足循环条件的情况下逐渐增加,直到g的值超过或等于f。

以下是修改后的代码:


#include<stdio.h>

int main() {
    int a = 10000;
    double c;
    c = a * 0.1;
    printf("小甲鱼的利息为%.2f", c);

    int count = 1;
    long long int g = 10000 + c;
    long long int f = 10000 + 10000 * 0.05;

    do {
      g = g + c;
      f = 10000 + f * 0.05;
      count = count + 1;
    } while (g <= f);

    printf("%d", count);

    return 0;
}


通过将循环条件修改为g <= f,count将在满足循环条件的情况下逐渐增加,直到g的值超过或等于f。这样,count就能正确地进行循环了。

希望能帮助到你!如果还有其他问题,请随时提问。

球一个最佳答案谢谢啦!这对我非常重要!{:10_254:}{:10_254:}{:10_254:}

Hengrui 发表于 2023-10-30 22:41:59

帮助我的回答输出的count还是2,为什么不是27呢
页: [1]
查看完整版本: count为啥不循环了