题目分析
来源: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";
}