题目粗心

给定N个输出,这些输出中只有在[-1000,1000]内并且位数在2位以内的数字才是非法的,对于不非法的输出间接输入相干信息,对于非法的数字须要计算平均值并进行输入

算法思路

此题惟一的考点就是判断输出是否非法,对于所有的非数字字符进行如下判断:

  • 1、如果该字符为"-"并且呈现在第一位,跳过
  • 2、如果该字符为小数点,则计算小数点前面的位数,如果大于2,则非法,否则统计小数点呈现的次数,呈现超过1次,则非法
  • 3、对于其余非数字字符均为非法字符。
  • 4、如果该数字为实数,如果在$[-1000,1000]$内,间接返回,否则非法,返回-1.

提交后果

AC代码

#include <cstdio>#include <iostream>using namespace std;/* * 判断输出的字符串是否非法 * 含有非数字字符,超过两个小数点,范畴在[-1000,1000]以外的都是非法字符 */double isLegal(const string &num){    int decimalCount = 0;// 小数点个数    int n = num.size();    for(int i=0;i<n;++i){        char c = num[i];        if(!(c>='0'&&c<='9')){            if(c=='-'&&i==0){                continue;            }else if(c=='.'){                // 呈现小数点                int rest = n-i-1;// 计算小数点前面的位数                if(rest>2){                    return -1;                }                ++decimalCount;                if(decimalCount>=2){                    return -1;                }            }else{                return -1;            }        }    }    // 肯定为数字    double x = stof(num);    if(x>=-1000&&x<=1000){        return x;    }else{        return -1;    }}int main(){    int N;    scanf("%d",&N);    string in;    int legalNum = 0;// 非法输出个数    double sum = 0;    for(int i=0;i<N;++i){        cin>>in;        double a = isLegal(in);        if(a!=-1){            sum += a;            ++legalNum;        }else{            cout<<"ERROR: "<<in<<" is not a legal number"<<endl;        }    }    if(legalNum>1){        printf("The average of %d numbers is %.2f",legalNum,sum/legalNum);    } else if(legalNum==1){        printf("The average of 1 number is %.2f",sum);    } else{        printf("The average of 0 numbers is Undefined");    }    return 0;}