有问题的程序代码:(全用if条件判断 )
void main(){
int a, b, c=0;
printf("please input a,b,c\n");
scanf("%d%d%d", &a, &b, &c);
if (a<=b<=c) {
printf("the order of the number is:\n");
printf("%d,%d,%d", a, b, c);
}
if (a <=c <= b) {
printf("the order of the number is:\n");
printf("%d,%d,%d", a, c, b);
}
if (b <=a<= c) {
printf("the order of the number is:\n");
printf("%d,%d,%d", b, a, c);
}
if (b <= c <= a) {
printf("the order of the number is:\n");
printf("%d,%d,%d", b, c, a);
}
if (c <= a <= b) {
printf("the order of the number is:\n");
printf("%d,%d,%d", c, a, b);
}
if (c <= b <= a) {
printf("the order of the number is:\n");
printf("%d,%d,%d", c, b, a);
}
getchar();
}
(if与else if配套使用的程序)
void main(){
int a, b, c=0;
printf("please input a,b,c\n");
scanf("%d%d%d", &a, &b, &c);
if (a<=b<=c) {
printf("the order of the number is:\n");
printf("%d,%d,%d", a, b, c);
}
else if (a <=c <= b) {
printf("the order of the number is:\n");
printf("%d,%d,%d", a, c, b);
}
else if (b <=a<= c) {
printf("the order of the number is:\n");
printf("%d,%d,%d", b, a, c);
}
else if (b <= c <= a) {
printf("the order of the number is:\n");
printf("%d,%d,%d", b, c, a);
}
else if (c <= a <= b) {
printf("the order of the number is:\n");
printf("%d,%d,%d", c, a, b);
}
else if (c <= b <= a) {
printf("the order of the number is:\n");
printf("%d,%d,%d", c, b, a);
}
}
其中,输入a,b,c三个数据时,三者数据均不相同
在使用if和else if配套的这个代码组时,最后输出的是唯一 一个结果,这是什么原因,有谁能帮我康康吗?
兄弟,是需要比较三个数大小然后按从小到大输出嘛。
不管输入什么数据都直接输出的原因是 if 与else if判断条件的问题,他们不能那样写,应该拆开,例如: a<=b && b<=c;
至于为什么兄弟可以看这个程序
a<b<c这个运算也是一个逻辑运算,其运算顺序等价与(a<b)<c,那么第一次运算后其值只可能是0或者是1,,如果后续再来个比1大的值返回值就为真。
当然是唯一的结果了,if 和elseif是互斥的,只要有一个条件满足,其它条件就不会再执行了。
这就是设置else if的原因啊。对于多个if语句来说,它们互不关联。而对于存在else if的语句来说,这些分支中一旦有一个为True,就不会再执行其他的分支了。当然,顺口提一句,else if其实是else {if {...}}的简写
if (a > 0) {}
else if (a < 0) {}
// 等价于:
if (a > 0) {}
else
{
if (a < 0) {}
}
这也是根本上,if和else if会互相关联的原因。
if (a<=b<=c) 应该为:if (a<=b && b<=c)
else if (a <=c <= b) 应为: else if (a <=c && c<= b)
else if (b <=a<= c) 应为: else if (b <=a && a<= c)
else if (b <= c <= a) 应为: else if (b <= c && c<= a)
else if (c <= a <= b) 应为: else if (c <= a && a<= b)
else if (c <= b <= a)应为: else if (c <= b && b<= a)
单独使用if会一个个判断,但是使用else if的话只会走一个分支,跟switch一样