c条件运算符
求奇偶数个数及各自平均数的例子,注释部分改成条件运算符怎么不行int main(){
int j,o,x,no,nj;
j=o=no=nj=0;
printf("enter some number:(0 to end)\n");
scanf("%d",&x);
while(x!=0){
/* if(x%2==0)
{
o++;
no+=x;
}
else if(x%2!=0)
{
j++;
nj+=x;
}*/
(x%2==0)?o++,no+=x:j++,nj+=x;
scanf("%d",&x);
}
printf("o have %d and its average:%f\nj have %d and its aversge:%f",o,(float)no/o,j,(float)nj/j);
return 0;
}
我来看看,先占个楼 运算符优先级未考虑
20行,逗号运算符的优先级低于条件运算符,应加括号
改为:(x%2==0)?(o++,no+=x):(j++,nj+=x);
修改后完整代码:
#include <stdio.h>
int main()
{
int j,o,x,no,nj;
j=o=no=nj=0;
printf("enter some number:(0 to end)\n");
scanf("%d",&x);
while(x!=0){
/* if(x%2==0)
{
o++;
no+=x;
}
else if(x%2!=0)
{
j++;
nj+=x;
}*/
(x%2==0)?(o++,no+=x):(j++,nj+=x);
scanf("%d",&x);
}
printf("o have %d and its average:%f\nj have %d and its aversge:%f",o,(float)no/o,j,(float)nj/j);
return 0;
}
运行结果
enter some number:(0 to end)
1
5
3
8
3
0
o have 1 and its average:8.000000
j have 4 and its aversge:3.000000
--------------------------------
Process exited after 9.498 seconds with return value 0
请按任意键继续. . .
页:
[1]