PAT A1108

本文介绍了一种使用C++实现的字符串处理函数,该函数用于判断字符串是否能转换为合法的浮点数,并计算一组字符串中所有合法浮点数的平均值。文章详细解释了如何检查字符串的格式,包括负号、小数点和数字的有效组合,确保转换后的数值在-1000到1000之间。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

clipboard.png
字符串处理,个人觉得最好的办法还是建立一个处理函数统一进行处理;

#include<iostream>
#include<cstdio>
#include<string>
using namespace std;
const int maxn = 101;
bool Judge(string s,double &x){
    int dot = 0,n1 = 0,n2 = 0;
    int i = 0;
    if(s[i]=='-') i++;
    for(;i < s.size();i++){
        if(s[i]=='.'){
            dot++;
            if(dot > 1) return 0;
        } else if(s[i]>='0'&&s[i]<='9'){
            if(dot) n2++;
            else n1++;
        } else return 0;
    }
    if(n2>2) return 0;
    sscanf(s.c_str(),"%lf",&x);
    if(x>=-1000&&x<=1000) return 1;
    return 0;
}       
int main(){
    int n,cnt = 0;
    double x,ans = 0;
    string s;
    cin >> n;
    for(int i = 0;i < n;i++){
        cin >> s;
        if(Judge(s,x)){
            cnt++;
            ans += x;
        } else {
            cout << "ERROR: " << s << " is not a legal number\n";
        }
    }
    if(cnt==1){
        printf("The average of 1 number is %.2f\n",ans);
        return 0;
    }
    printf("The average of %d numbers is ",cnt);
    if(cnt) printf("%.2f\n",ans/cnt);
    else cout << "Undefined\n";
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值