标题:如何实现输入0时结束输入?
只看楼主
scibar
Rank: 1
等 级:新手上路
帖 子:25
专家分:6
注 册:2018-4-23
结帖率:80%
已结贴  问题点数:20 回复次数:5 
如何实现输入0时结束输入?
题目要求输入一行整数直到输入0,然后计算奇数和偶数(0除外)的个数以及求出它们的平均值。
#include<stdio.h>
int main(void)
{
    int a;
    int n_even = 0;
    int n_odd = 0;
    int sum_even = 0;
    int sum_odd = 0;
    float average_even;
    float average_odd;
   
    while(scanf("%d",&a)==1)
    {
   
        if((a%2)==0 && a!='0')
        {
            
          n_even++;
          sum_even+=a;
        }  
          else
          {
            n_odd++;
            sum_odd+=a;
          }
            
        
    }
    average_even=sum_even/n_even;
    average_odd=sum_odd/n_odd;
    printf("there are %d even number,%d odd number.\n",n_even,n_odd);
    printf("the average of all even numbers is %.1f.\n",average_even);
    printf("the average of all odd numbers is %.1f.\n",average_odd);
    return 0;
}
搜索更多相关主题的帖子: 输入 结束 int even printf 
2018-04-26 13:38
sunus
Rank: 4
等 级:业余侠客
威 望:3
帖 子:47
专家分:234
注 册:2017-10-10
得分:20 
while里加一句if(a==0) break;
2018-04-26 14:13
随新飞翔
Rank: 2
等 级:论坛游民
帖 子:10
专家分:14
注 册:2018-3-16
得分:0 
while(scanf("%d",&a)!=0)
2018-04-26 14:47
随新飞翔
Rank: 2
等 级:论坛游民
帖 子:10
专家分:14
注 册:2018-3-16
得分:0 
其实感觉分开写比较好,  scanf("%d",&a);
while(a!=0)
2018-04-26 14:49
rjsp
Rank: 20Rank: 20Rank: 20Rank: 20Rank: 20
等 级:版主
威 望:507
帖 子:8890
专家分:53117
注 册:2011-1-18
得分:0 
#include <stdio.h>

int main( void )
{
    unsigned n_even=0, n_odd=0;
    unsigned sum_even=0, sum_odd=0;
    for( int val; scanf("%d",&val)==1 && val!=0; )
    {
        if( val%2==0 )
        {
            sum_even += val;
            ++n_even;
        }
        else
        {
            sum_odd += val;
            ++n_odd;
        }
    }
    printf( "there are %u even numbers, %u odd numbers.\n", n_even, n_odd );
    printf( "the average of all even numbers is %g.\n", n_even!=0 ? sum_even*1.0/n_even : 0.0 );
    printf( "the average of all odd numbers is %g.\n", n_odd!=0 ? sum_odd*1.0/n_odd : 0.0 );
}
2018-04-26 16:48
vvvcuu
Rank: 9Rank: 9Rank: 9
等 级:贵宾
威 望:12
帖 子:353
专家分:1253
注 册:2014-4-22
得分:0 
回复 3楼 随新飞翔
这么写是不对的。scanf()的返回值是读入的复合格式要求的字符的个数,不是读入的字符的值。

scanf()原型是int scanf (const char*, ...);

代码测试环境:  WinXP+C-Free5.0.
2018-04-26 17:18



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-486406-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.030330 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved