题目:https://pintia.cn/problem-sets/994805260223102976/problems/994805272659214336
经验总结:
首先判断是否是负数,并做上标记。之后判断是否含有小数点,如果没有,代表一个整数,循环判断是否是合法整数。如果有小数点并且判断只有一个小数点,代表一个实数,循环判断是否是合法实数。之后用stod(string转double)。
记:合理利用auto,能减少编程量。
记:to_string(转string)
函数原型:
string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val)
记:stod(string转double)、stoi(string转int)、stol、stoul、stoll、stoull、stof、stold
记:size_type 和 int 最好不要用来做对比,size_type 与机器无关,而int与机器有关,如果刚好两者长度不一样就尴尬了。。
记:size_type 是 unsigned 型的,所以具体使用的时候要避免出现 for (vector::size_type i = 100; i>0; i–) 这样的语句,因为i永远也不会小于0
C++代码:
#include <iostream>
#include <cstdio>
#include <iomanip>
#include <typeinfo>
using namespace std;
const double error = 1111;
double check(string s){
double ans = 0;
bool isfushu = false;
if(s[0]=='-'){
isfushu = true;
s = s.substr(1);
}
auto index = s.find_first_of('.'); //合理利用auto
// if(typeid(index)==typeid(string::size_type)){
// cout<<"类型匹配成功!"<<endl;
// }
if(index == string::npos){ //如果没有小数点
for(int i = 0;i<s.size();i++){
if(!(s[i]>='0'&&s[i]<='9')){
return error;
}
}
}else if(index == s.find_last_of('.')){ //如果有小数点
if(index<s.size()-3){
return error;
}
for(int i = 0;i<s.size();i++){
if(!(s[i]>='0'&&s[i]<='9')&&s[i]!='.'){
return error;
}
}
}else {
return error;
}
ans = stod(s);
if(isfushu){
ans *= -1;
}
if(ans>1000||ans<-1000){
return error;
}
return ans;
}
int main()
{
int n;
cin>>n;
double ans = 0;
int K = 0;
while(n--){
string s;
cin>>s;
double num = check(s);
if(error == num){
cout<<"ERROR: "<<s<<" is not a legal number"<<endl;
}else{
ans += num;
K++;
}
}
if(K == 0){
cout<<"The average of 0 numbers is Undefined"<<endl;
}else if(K == 1){
cout<<fixed<<setprecision(2)<<"The average of 1 number is "<<ans<<endl;
}else{
cout<<fixed<<setprecision(2)<<"The average of "<<K<<" numbers is "<<ans/K<<endl;
}
return 0;
}
本文介绍了一种使用C++处理字符串输入,判断其是否为合法的整数或浮点数的方法,并通过stod函数将字符串转换为double类型。文章详细解释了如何检查字符串的格式,包括处理负数和小数点,以及如何计算一系列输入的平均值。
224

被折叠的 条评论
为什么被折叠?



