当我给a和b赋最大值时,代码可以完美地工作,但是当给c或d输入最大值时,代码不起作用。有人可以帮我吗?
我已经访问过网站并进行了研究,但找不到任何东西。
#include<stdio.h>
void main(void) {
int a, b, c, d;
scanf("%d %d %d %d", &a, &b, &c, &d);
printf("the enter no.: is %d %d %d %d\n", a, b, c, d);
if(a > b) {
if(a > c) {
if(a > d) {
printf("%d is greater",a);
}
}
} else if(b > a) {
if(b > c) {
if(b > d) {
printf("%d is greater", b);
}
}
} else if(c > a) {
if(c > b) {
if(c > d) {
printf("%d is greater", c);
}
}
} else if(d > a) {
if(d > c) {
if(d > b) {
printf("%d is greater", d);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
所有变量的输出应该相同,但是a和b仍提供预期的输出,而c和d却没有提供。
您的处理方式是错误的,例如输入2 1 4 3 if(a>b)为true但if(a>c)为false,因此您什么也不做,也不会检测到最大数
出于您的问题,我还建议您检查4个有效的int,然后输入检查scanf("%d %d %d %d",&a,&b,&c,&d)返回4
提案 :
#include<stdio.h>
int main()
{
int a,b,c,d;
if (scanf("%d %d %d %d",&a,&b,&c,&d) != 4)
fprintf(stderr, "error while entering the 4 values\n");
else {
printf("the enter no.: is %d %d %d %d\n",a,b,c,d);
int max = a;
if (b > max)
max = b;
if (c > max)
max = c;
if (d > max)
max = d;
printf("the greater is %d\n", max);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编译和执行:
pi@raspberrypi:/tmp $ gcc -pedantic -Wall -Wextra m.c
pi@raspberrypi:/tmp $ ./a.out
1 2 4 3
the enter no.: is 1 2 4 3
the greater is 4
Run Code Online (Sandbox Code Playgroud)
当然,还有另一种方法可以不记住所有数字