题目描述
知识点: 模拟
思路: 就是模拟,读入
自己实现的纯模拟代码,较为复杂一丢丢
#include<iostream>
using namespace std;
int n,cnt = 0;
double string_to_double(string s){
int is_minus = 1;
if(s[0] == '-') {
is_minus = -1;
s = s.substr(1);
}
double res = 0;
int index = s.find('.');
if(index == -1) index = s.length();
double k = 1;
for(int i = index-1;i >= 0;i--){
res += (s[i]-'0')*k;
k *= 10;
}
k = 0.1;
for(int i = index+1;i < s.length();i++){
res += (s[i]-'0')*k;
k *= 0.1 ;
}
res *= is_minus;
return res;
}
double jud(string s){
double res = 0;
string cop = s;
if(s[0] == '-')
s = s.substr(1);
int index = s.find('.');
for(int i = 0;i < s.length();i++){
if(s[i] > '9' || s[i] < '0' && index != i) {
printf("ERROR: %s is not a legal number\n",cop.c_str());
return 0;
}
}
if(index == 0 || index < s.length() - 3){
printf("ERROR: %s is not a legal number\n",cop.c_str());
return 0;
}
res = string_to_double(cop);
if(res > 1000 || res < -1000)
{
printf("ERROR: %s is not a legal number\n",cop.c_str());
return 0;
}
cnt++;
return res;
}
int main(){
double res = 0;
cin>>n;
for(int i = 0;i < n;i++){
string s;
cin>>s;
res += jud(s);
}
if(cnt > 1)
printf("The average of %d numbers is %.2lf",cnt,res/cnt);
else if(cnt == 0) printf("The average of 0 numbers is Undefined");
else if(cnt == 1) printf("The average of %d number is %.2lf",cnt,res/cnt);
return 0;
}
本题有另外一个函数stof,可以将字符串转为double类型,但是如果"32.552as"这种字符串也会进行转换,拿出前面几位,他还接收一个参数表示用了几位进行转换。
copy的题解
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int cnt = 0; // 合法数字个数
double sum = 0; // 合法数字总和
while (n -- )
{
string num;
cin >> num;
double x;
bool success = true;
/*
不加try catch报错terminate called after throwing an instance of 'std::invalid_argument'
what(): stof(若传入不可转化为浮点型的字符串)会抛出异常
*/
try
{
size_t idx = sizeof(num); // size type 用来记录大小的数据类型
x = stof(num, &idx); // 字符串转换为float型
// stof判断"5.2abc"这类字符串时视"5.2"为合法,"abc"不合法,但实际上5.2abc不合法
if (idx < num.size()) success = false; // 经stof处理后变短的字符串不合法
}
catch(...) // 捕捉所有类型的异常
{
success = false; // 所有不合法的输入数字都设为error
}
if (x < -1000 || x > 1000) success = false;
int k = num.find('.');
if (k != -1 && num.size() - k > 3) success = false;// 不超过2个小数位(最后一位是num.size()-1)
if (success) cnt ++, sum += x;
else printf("ERROR: %s is not a legal number\n", num.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 1 number is %.2lf\n", sum);
else puts("The average of 0 numbers is Undefined");
return 0;
}
作者:魔法学徒
链接:https://www.acwing.com/solution/content/125749/
来源:AcWing