|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
求奇偶数个数及各自平均数的例子,注释部分改成条件运算符怎么不行
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
- 请按任意键继续. . .
复制代码
|
|