PAT 1054. 求平均值 (20)

。。。第一眼感觉题目很慌啊,要一个个判断。
然后网上搜了题解,顿时感觉,学到了!
这个是题解的地址:http://www.liuchuo.net/archives/617
用sscanf(a,%lf,&temp)a为字符串char*,temp为double类型的数字。直接将字符串直接转化成数字。
然后因为输出格式没注意。。。wa了几发。。。尴尬
下面是代码

#include <iostream>
#include <cstdio>
#include <string.h>
using namespace std;
int main() 
{
    int t;
    cin>>t;
    double temp=0,sum=0.0;
    int cnt=0;
    while(t--)
    {   
        char s[50];
        char a[50];
        scanf("%s", s);
        sscanf(s,"%lf",&temp);
        sprintf(a,"%.2lf",temp);
        int flag=0;
        for(int i=0;i<strlen(s);i++)
        {
            if(s[i]!=a[i])
            flag=1;
        }
        if(flag||temp<-1000||temp>1000)
        {
            printf("ERROR: %s is not a legal number\n",s);
            continue;
        }
        else
        {
            sum+=temp;
            cnt++;
        }
    }
    if(cnt==0)
        printf("The average of 0 numbers is Undefined\n");
    else if(cnt==1)
        printf("The average of 1 number is %.2lf\n",sum);
    else
        printf("The average of %d numbers is %.2lf\n",cnt,sum*1.0/cnt);
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值