PAT A1108 Finding Average [字符串处理]

题目描述

链接
判断是否合法字符串

分析

  • 巧解
    sscanf(s1, "%lf", &num) – 将字符串s1中按格式写入变量num
    sprintf(s2, "%.2f", num) – 将变量num按格式写入字符串s2
  • 我的笨方法
    • 正数和负数判断
    • 判断小数点的个数及位置,及小数点后的位数,及数字的大小
    • stof的应用
  • 一个巨坑的地方是!!!如果只有一个数,那么英文用单数!!!即number,而不是numbers

代码1

#include <iostream>
#include <cstdio>
#include <string.h>
using namespace std;
int main() {
    int n, cnt = 0;
    char a[50], b[50];
    double temp, sum = 0.0;
    cin >> n;
    for(int i = 0; i < n; i++) {
        scanf("%s", a);
        sscanf(a, "%lf", &temp);
        sprintf(b, "%.2f",temp);
        int flag = 0;
        for(int j = 0; j < strlen(a); j++)
            if(a[j] != b[j]) flag = 1;
        if(flag || temp < -1000 || temp > 1000) {
            printf("ERROR: %s is not a legal number\n", a);
            continue;
        } else {
            sum += temp;
            cnt++;
        }
    }
    if(cnt == 1)
        printf("The average of 1 number is %.2f", sum);
    else if(cnt > 1)
        printf("The average of %d numbers is %.2f", cnt, sum / cnt);
    else
        printf("The average of 0 numbers is Undefined");
    return 0;
}

代码2

#include<bits/stdc++.h>
using namespace std;


bool check(string s){
    int len = s.length();
    if(s[0] != '-' &&  (s[0] < '0' || s[0] > '9')) return false; //正负号
    int dot_cnt = 0; 
    int dot_loc = -1;
    for(int i=1;i<len;i++){
        if(s[i] == '.'){ //统计点数
            dot_cnt++;
            if(dot_loc == -1) dot_loc = i;
            continue;
        }
        if((s[i] < '0' || s[i] > '9') && s[i] != '.') return false; //是否为非数字字符
    }
    if(dot_cnt > 1) return false; //小数点个数
    else if(dot_cnt == 1){
        if(len - 1 - dot_loc > 2) return false;  //小数点后位数
    }
    if(stof(s)<-1000 || stof(s)>1000) return false; //数字范围
    return true;
}

int main(){
    int n;
    string s;
    cin>>n;
    double sum = 0;
    int cnt = 0;
    for(int i=0;i<n;i++){
        cin>>s;
        if(check(s)){
            cnt++;
            sum += stof(s);
        }else{
            cout<<"ERROR: "<<s<<" is not a legal number"<<endl;
        }
    }
    if(cnt == 0){
        cout<<"The average of 0 numbers is Undefined"<<endl;
    }else if(cnt != 1){
        printf("The average of %d numbers is %.2f\n", cnt, sum/cnt);
    }else{
        printf("The average of 1 number is %.2f\n", sum);
    }
}
posted @ 2019-09-02 19:34  Doragd  阅读(185)  评论(0编辑  收藏  举报