1108 Finding Average(20 分)

版权声明:https://github.com/godspeedcurry 欢迎加好友哦 https://blog.csdn.net/qq_38677814/article/details/82079145

1108 Finding Average(20 分)
The basic task is simple: given N real numbers, you are supposed to calculate their average. But what makes it complicated is that some of the input numbers might not be legal. A legal input is a real number in [−1000,1000] and is accurate up to no more than 2 decimal places. When you calculate the average, those illegal numbers must not be counted in.

Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤100). Then N numbers are given in the next line, separated by one space.

Output Specification:
For each illegal input number, print in a line ERROR: X is not a legal number where X is the input. Then finally print in a line the result: The average of K numbers is Y where K is the number of legal inputs and Y is their average, accurate to 2 decimal places. In case the average cannot be calculated, output Undefined instead of Y. In case K is only 1, output The average of 1 number is Y instead.
模拟题,条件比较多
写个函数检查一下输入就可以了
数据比较水,代码简陋了一点
–1.2
1.234
1..
11a

#include <bits/stdc++.h>
using namespace std;
double res;
#define eps 1e-8
int sgn(double a){
    return a<-eps?-1:a<eps?0:1;
}
bool check(string s){
    int pt=0;
    int jian=0;
    int pos_pt=-1;
    for(int i=0;i<s.size();i++){
        if(isalpha(s[i])){
            return false;
        }
        else if(s[i]=='.'){
            if(++pt==2) return false;
            pos_pt=i;
        }
        else if(s[i]=='-'){
            if(++jian==2) return false;
        }
    }
    if(pt!=0){
        if(s.size()-pos_pt>=4) return false;
    }
    sscanf(s.c_str(),"%lf",&res);
    if((res+1000)<-eps||res-1000>eps) return false;
    return true;
}
int main(){
    int n;cin>>n;
    double all=0;
    int cnt=0;
    for(int i=1;i<=n;i++){
        string a;
        cin>>a;
        if(check(a)){
            ++cnt;
            all+=res;
        }
        else{
            printf("ERROR: %s is not a legal number\n",a.c_str());
        }
    }
    if(!cnt){
        printf("The average of 0 numbers is Undefined\n");
    }
    else if(cnt==1) printf("The average of 1 number is %.2lf\n",all/cnt);
    else printf("The average of %d numbers is %.2lf\n",cnt,all/cnt );
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_38677814/article/details/82079145
今日推荐