PAT 1108 Finding Average

本文介绍了一种用于判断字符串是否为合法数字的方法,并演示了如何将合法的字符串转换为数字类型。通过一个C++程序示例,我们探讨了字符串和数字之间的相互转换过程,包括对小数点和负数的支持,以及对非法字符的错误处理。

注意字符串和数字之间的相互转换

#include <iostream>
#include<string>
#include <cmath>
using namespace std;
bool judge(string& string1){
    int count=0;
    for (int i1=0;i1<string1.length();i1++) {
        char i=string1[i1];
        if (!(i=='.'||isdigit(i)||i=='-')){
            return false;
        }
        if(i=='.'){
            count++;
            if(string1.length()-i1>3){
                return false;
            }
        }
        if(count==2){
            return false;
        }
    }
    return true;
}
int main() {
//    std::cout << "Hello, World!" << std::endl;
    int N;
    cin>>N;
    double sum=0;
    int count=0;
    for (int i = 0; i < N; ++i) {
        string s;
        cin>>s;
        if(judge(s)){
            double val;
            sscanf(s.c_str(),"%lf",&val);//字符串转化为数字
            if (abs(val)>1000){
                printf("ERROR: %s is not a legal number\n",s.c_str());
                continue;
            }
            sum+=val;
            count++;
        } else{
            printf("ERROR: %s is not a legal number\n",s.c_str());
        }
    }
    if(count==0){
        cout<<"The average of 0 numbers is Undefined";
        return 0;
    } else if(count==1){
        cout<<"The average of 1 number is ";
        printf("%.2f\n",sum);
        return 0;
    }
    cout<<"The average of "<<count<<" numbers is ";
    printf("%.2f\n",sum/count);
    return 0;
}













 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值