*浙大PAT甲级 1108

一个很繁琐的题,使用字符串数组,对于每个字符串需要判断第一个符号是否为负,以及是否有小数点以及个数,还需判断是否超过[-1000,1000]的范围。还有如果合法数为1个时,number后面不加s,如果为0个则用Undefined来代替Y 。

AC代码:

#include<iostream>
#include<map>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<cstring>
#include<set>
#include<stack>
#include<cmath>
#include<vector>
#include<hash_map>
#define ll long long
#define inf 24*60*60
using namespace std;
string a[105];
int main()
{
    int n;
    scanf("%d",&n);
    double ans=0;
    int ci=0;
    for(int i=0;i<n;i++)
    {
        cin>>a[i];
    }
    for(int i=0;i<n;i++)
    {
        int flag=0;
        double sum=0;
        int j=0;
        if(a[i][0]=='-')
        {
            flag=1;
            j++;
        }
        int flag1=0;
        double d=0.1;
        int flag2=0;
        for(;j<a[i].size();j++)
        {
            if(a[i][j]=='.'&&flag1==0)
            {
                flag1=1;
            }
            else if(a[i][j]>='0'&&a[i][j]<='9')
            {
                    if(flag1==0)
                    {
                        sum*=10;
                        sum+=a[i][j]-'0';
                        if(sum>1000)
                        {
                            cout<<"ERROR: "<<a[i]<<" is not a legal number"<<endl;
                            flag2=1;
                            break;
                        }
                    }
                    else
                    {
                        double ok=(a[i][j]-'0')*d;
                        d*=0.1;
                        if(fabs(d-0.0001)<1e-5)
                        {
                            cout<<"ERROR: "<<a[i]<<" is not a legal number"<<endl;
                            flag2=1;
                            break;
                        }
                        sum+=ok;
                        if(sum>1000)
                        {
                            cout<<"ERROR: "<<a[i]<<" is not a legal number"<<endl;
                            flag2=1;
                            break;
                        }
                    }
            }
            else
            {
                cout<<"ERROR: "<<a[i]<<" is not a legal number"<<endl;
                flag2=1;
                break;
            }

        }
        if(flag2==0)
        {
            sum=flag==1?-sum:sum;
            ci++;
            ans+=sum;
        }

    }
    if(ci==0)
    {
        printf("The average of 0 numbers is Undefined");
    }
    else if(ci>1)
    {
        printf("The average of %d numbers is %.2lf",ci,ans/ci);
    }
    else
    {
        printf("The average of 1 number is %.2lf",ans);
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值