PAT甲级 求平均值 (字符串模拟 / stof字符串转浮点数/整形 try catch语句)

求平均值

题目大意:
基本任务非常简单:给定 N 个实数,请你计算它们的平均值。
但是令事情变得复杂的是,某些输入数字可能不合法。
合法输入数字指 [−1000,1000] 范围内的精确到不超过 2 个小数位的实数。
在计算平均值时,不得将这些非法数字计算在内。

输入格式
第一行包含整数 N。
第二行包含 N 个输入数字,数字之间用空格隔开。

输出格式
按照输入的顺序,对于每个输入的非法数字,在一行中输出 ERROR: X is not a legal number,其中 X 是非法输入。
最后一行,输出 The average of K numbers is Y,其中 K 是合法输入的数量,Y 是它们的平均值,注意保留两位小数。

如果平均值无法计算,则将 Y 替换为 Undefined。
如果 K 仅为 1,则输出 The average of 1 number is Y。

数据范围
1≤N≤1000
输入样例1:
7
5 -3.2 aaa 9999 2.3.4 7.123 2.35
输出样例1:
ERROR: aaa is not a legal number
ERROR: 9999 is not a legal number
ERROR: 2.3.4 is not a legal number
ERROR: 7.123 is not a legal number
The average of 3 numbers is 1.38

输入样例2:
2
aaa -9999
输出样例2:
ERROR: aaa is not a legal number
ERROR: -9999 is not a legal number
The average of 0 numbers is Undefined

解题思路:
看完dxl的视频学到了在c++里写try catch的操作,dxltql。
stof是字符串转浮点型 , stoi是字符串转整形
注意要在try catch里写,如果转换失败 flag 为false;
如果是 12.53aac87 转换的话 结果为 12.53
size_t 代表转换后数字在原字符串中占几位

Code:

#include<iostream>
#include<cstdio>
#include<string>
#include<ctime>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<stack>
#include<climits>
#include<queue>
#include<map>
#include<set>
#include<sstream>
#include<cassert>
#include<bitset>
#include<unordered_set>
#include<unordered_map>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int inf=0x3f3f3f3f;
const int maxn=1e5+7;



int main()
{
    int n,cnt=0;
    double sum=0;
    cin>>n;
    while(n--){
    	string num;
    	cin>>num;
    	double x;
    	bool flag=true;
    	try{
    		size_t idx;                 //转换后数字的位数/大小  >=0 非负整数 
    		x=stof(num,&idx);          //stoi 字符串转整形 
    		
    		if(idx<num.size()) flag=false;
		}
		catch(...){
			flag=false;
		}
		if(x<-1000||x>1000) flag=false;
		int k=num.find('.');                          //找到字符串中‘.’的位置
		if(k!=-1&&num.size()-k>3) flag=false;
		
		if(flag) cnt++,sum+=x;
		else printf("ERROR: %s is not a legal number\n",num.c_str()); //直接输出num 不合法??
	}
    
    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/cnt);
	else printf("The average of 0 numbers is Undefined\n");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43872264/article/details/107844564