1215787625 发表于 2023-10-30 11:06:00

为什么输入3452时输出与预期不符

#include <stdio.h>
#include <math.h>
int main()
{
int a;
scanf("%d",&a);
int x,y;
y = a;
do{
x = a % 10;
a /= 10;
if(x == 5||x==9){
printf("%d",y%45);
return 0;
}
else
printf("Not include!");
}while(x == 0);
   return 0;
}

isdkz 发表于 2023-10-30 11:06:11

问题的原因在于代码中的循环条件不正确,导致在输入3452时输出与预期不符。

在代码中,循环条件while(x == 0)应该改为while(a != 0) ,以确保在 a 不等于 0 的情况下继续循环。

修改后的代码如下:

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

int main()
{
    int a;
    scanf("%d", &a);
    int x, y;
    y = a;
    do {
      x = a % 10;
      a /= 10;
      if (x == 5 || x == 9) {
            printf("%d", y % 45);
            return 0;
      } else {
            printf("Not include!");
      }
    } while (a != 0);
   
    return 0;
}


这样修改后,输入3452时将输出 "Not include!",符合预期结果。
页: [1]
查看完整版本: 为什么输入3452时输出与预期不符