C语言和序题

来源:百度知道 编辑:UC知道 时间:2024/04/29 07:51:06
#include <stdio.h> //程序找最大数和次大数
#include <math.h>
int main()

{
int a,b,c,d,sed,max;
printf("plaes input four number\n");
scanf("%d%d%d%d",&a,&b,&c,&d);
if (a>b)
{
max=a;
sed=b;
}
else{

max=b;
sed=a;
}

if(max>c){

sed>c?sed:sed=c;

}
else{
sed=max;
max=c;

}
if(max>d){

sed>d?sed:sed=d; //问题好像出在这里

}
else{

sed=max;
max=d;
}

printf("max=%d,sed=%d",max,sed);
return 0;

}

sed>d?sed:sed=d; 在的时候输 9 2 7 2 在linux gcc
下结果是 max=9, sed=2
注释掉,就正常了;
可这么一来输入:9 4 5 6 输出的时候max=9,sed=5了
这程序怎么一回事啊?

sed>c?sed:sed=c;和sed>d?sed:sed=d; 都用错了应该改为sed=sed>c?sed:c;和sed=sed>d?sed:d;

sed>d?sed:sed=d;
=的优先级比?:要低,所以这句话实质上就是sed=d;而不是
sed>d?sed:(sed=d);

应该改成if(sed<d) sed=d;
上面同样要改成if(sed<c) sed=c;

建议你先对数排序,那样最大和第二最大值很好确定了