PTA刷题Basic篇——1054.求平均值——Day(27)

题目描述

在这里插入图片描述求出合法数据的平均值并输出相应语句。对于不合法的数据我们要输出ERROR语句。

题目分析

这个问题其实乍一看挺简单的,但是有很多细节处理起来很麻烦。首先,我们需要写一个函数,对于每一个输入的字符串进行判断其是否合理。如果这个字符串中有两个小数点或者有一个小数点但是精确位数大于2则都不合理,如果不是数字也淘汰。
在我们的主函数中,我们逐一输入字符串,判断其是否合理,如果不合理就输出对应的ERROR语句。如果合理则记录下来留着计算平均值。
计算平均值时保留小数点后两位,且需要输出相应语句,如果全部不合理,则输出The average of 0 numbers is Undefined
还有一个细节,如果只有一个数计算平均值,则对应输出的是number,否则为numbers

代码

#include <cstdio>
#include <cstring>
#include <string>
#include <iostream>
#include <cmath>
#include <algorithm>
#include <iomanip>
using namespace std;
bool check(string &str)
{
    bool flag=false;
    int i=0,a=0,b=0;
    if(str[i]=='-') i++;
    for(;i<str.size();i++)
    {
        if((!isdigit(str[i]))&&(str[i]!='.')) return false;
        if(str[i]=='.') 
        {
            a++;
            flag=true;
            continue;
        }
        //有小数点的话,小数点后最多有两位数字
        if(flag)
            b++;
    }
    //stod将str类型的变量转化为double类型
    if(a>1||b>2||stod(str)>1000||stod(str)< -1000) return false;
    else return true;
}
int main()
{
    int n,count=0;
    string str;
    double sum=0;
    cin>>n;
    for(int i=0;i<n;i++) 
    {
        cin>>str;
        if(!check(str)) cout<<"ERROR: "<<str<<" is not a legal number\n";  
        else if(check(str)){
            count++;
            sum+=stod(str);
        }
    }
    if(count==0) cout<<"The average of 0 numbers is Undefined\n";
    else if(count==1) cout<<"The average of 1 number is "<<fixed<<setprecision(2)<<sum<<endl;
    else printf("The average of %d numbers is %.2f\n",count,sum/count);
    return 0;
}

答题用时21min
Q54——finish√

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值