PAT甲级1108 Finding Average :[C++题解]stof、字符串变成浮点数、try和catch捕获异常、C++语法题

题目分析

在这里插入图片描述
在这里插入图片描述
来源:acwing

分析:
C++中有函数stoi表示把string 变成int,还有函数stof,表示把string变成float。如果是合法数字的话,stof就将其变成数,不是合法数字的话,会抛出异常。

size_t idx; //这里是类型size_t,不是int
stof(s,&idx); //idx存的是用到字符串s中几个字符,如果全用到, 则是idx==s.size()

stof的英文释义如下:读者可以参阅。

float       stof( const std::string& str, std::size_t* pos = 0 );
#功能
Function discards any whitespace characters (as determined by   
std::isspace()) until first non-whitespace character is found. 
Then it takes as many characters as possible 
to form a valid floating-point representation 
and converts them to a floating-point value.
#Parameters:两个参数
str	-	the string to convert
pos	-	address of an integer to store the number of characters processed
#Return value:返回值
The string converted to the specified floating point type.

#Exceptions:抛出异常
std::invalid_argument if no conversion could be performed

std::out_of_range if the converted value would fall out of the range of the result type or if the underlying function (strtof, strtod or strtold) sets errno to ERANGE.

所以需要用try{}和catch{}来捕获异常。

判断字符串是否是浮点数的写法
//3.13abc这样的数也会转成double,不过存的是3.13,用到的字符个数idx =4,后面的abc会被抛弃。所以x =3.13.

        double x;
        bool success = true; 
        try{
            size_t idx; //用了几个字符
            x =stof(s,&idx); 
            if(idx < s.size()) success = false;
            
        }
        //任何类型的异常:用...表示
        //如果有异常,就执行下面的语句
        catch(...){
            success = false;
        }

AC代码

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

const int N =1010;

int main(){
    int n;
    cin >>n ;
    int cnt = 0;
    double sum = 0;
    while(n--){
        string s;
        cin >> s;
        double x;
        bool success = true;
        try{
            size_t idx; //用了几个字符
            x =stof(s,&idx);
            if(idx < s.size()) success = false;
            
        }
        //任何类型的异常:用...表示
        //如果有异常,就执行下面的语句
        catch(...){
            success = false;
        }
        
        if( x< -1000 || x > 1000) success  =false;
        int k = s.find(".");
        //不是两位小数
        if(k!= -1 && s.size()-1-k>2) success = false;
        
        if(success) cnt++, sum += x;
        else  printf("ERROR: %s is not a legal number\n",s.c_str());
    }
    if(cnt>1) printf("The average of %d numbers is %.2lf\n",cnt, sum/cnt);
    else if(cnt == 1) printf("The average of %d number is %.2lf\n",cnt, sum);
    else cout<<"The average of 0 numbers is Undefined";
}

在这里插入图片描述

题目来源

PAT甲级1108 Finding Average

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值