PAT甲级1108 Finding Average (20分)|C++实现

    科技2022-08-01  95

    一、题目描述

    原题链接

    Input Specification:

    ​​Output Specification:

    Sample Input 1:

    7 5 -3.2 aaa 9999 2.3.4 7.123 2.35

    Sample Output 1:

    ERROR: aaa is not a legal number ERROR: 9999 is not a legal number ERROR: 2.3.4 is not a legal number ERROR: 7.123 is not a legal number The average of 3 numbers is 1.38

    Sample Input 2:

    2 aaa -9999

    Sample Output 2:

    ERROR: aaa is not a legal number ERROR: -9999 is not a legal number The average of 0 numbers is Undefined

    二、解题思路

    这道题纯用字符串处理还是比较麻烦的,但是如果掌握了sscanf和sprintf函数的话,就可以很简便地解决了,我的代码是比较复杂的,看个乐子就行… 建议大家看看柳神的代码: 1108. Finding Average (20)-PAT甲级真题

    三、AC代码

    #include<iostream> #include<string> #include<algorithm> #include<cstdio> #include<vector> #include<cmath> using namespace std; vector<double> valid; double to_num(string str) { int sze = str.size(), st; bool flagdot = false; int posdot = -1; double ans = 0.0; double acc = 0.0; if(str[0] == '-') st = 1; else st = 0; for(int i=st; i<sze; i++) { if(str[i] == '.') { flagdot = true; posdot = i; continue; } if(flagdot) acc = acc*10 + str[i] - '0'; else ans = ans*10 + str[i] - '0'; } if(flagdot) sze-1-posdot == 2 ? acc *= 0.01 : acc *= 0.1; ans += acc; if(st == 1) ans = -ans; return ans; } bool check(string str) { int sze = str.size(), cntdots = 0, posdot; if(str[0] == '.') return false; if(sze == 1 && !(str[0]>='0' && str[0]<='9')) return false; for(int i=0; i<sze; i++) { if(str[i] >= '0' && str[i] <= '9') continue; else { if(i==0 && str[i] == '-') continue; if(str[i] == '.') { cntdots++; posdot = i; } else return false; } if(cntdots > 1) return false; } if(cntdots == 1 && sze - posdot - 1 > 2) return false; double num = to_num(str); if(num < -1000.0 || num > 1000.0) return false; else return true; } int main() { string str; int N; scanf("%d", &N); for(int i=0; i<N; i++) { cin >> str; if(check(str)) valid.push_back(to_num(str)); else cout << "ERROR: " << str << " is not a legal number" << endl; } double sum=0.0, avg; int sze = valid.size(); if(sze == 1) { printf("The average of 1 number is %.2f\n", valid[0]); return 0; } else if(sze == 0) printf("The average of 0 numbers is Undefined\n", sze); else { for(int i=0; i<sze; i++) sum += valid[i]; avg = sum/sze; printf("The average of %d numbers is %.2f\n", sze, avg); } return 0; }
    Processed: 0.013, SQL: 8