PTA 求平均值 (20分) (普通方法和正则两种)

求平均值

一般方法:

#include<bits/stdc++.h>
using namespace std;
bool islegal(string s){
	int len=s.size();
	int f=1,i=0,j;
	if(s[i]=='-'){
		i++;
	}
	for(;i<len;++i){
		if(s[i]=='.'){
			i++;
			break;
		}
		if(!isdigit(s[i]))
			return false;
	}
	for(j=i;j<len;++j){
		if(!isdigit(s[j]))
			return false;
	}
	if(j-i>2 || j!=len)
		return false;
	double sum=atof(s.c_str());
	if(sum>1000 || sum<-1000)
		return false;
	return true;
}
int main()
{
	int n,cnt=0;
	double sum=0;
	cin >> n;
	while(n--){
		string s;
		cin >> s;
		if(islegal(s)){
			cnt++;
			sum+=atof(s.c_str());
		}
		else
			cout << "ERROR: " << s << " is not a legal number\n";
	}
	if(cnt==0)
		printf("The average of %d numbers is Undefined\n",cnt);
	else if(cnt>1)
		printf("The average of %d numbers is %.2f\n",cnt,sum/cnt);
	else if(cnt==1)
		printf("The average of 1 number is %.2f\n",sum);
	return 0;
} 

正则方法:

#include<iostream>
#include<regex>
using namespace std;
int main() {
	regex pattern("[+-]?([1-9][0-9]*|0)(.[0-9]{0,2})?");
	int n;
	scanf("%d",&n);
	double x;
	int k=0;
	double s=0;
	char x0[110000];
	for(int i=0; i<n;) {
		scanf("%s",x0);
		bool ismatch = regex_match(x0, pattern);
		if(ismatch==true) {
			int j=sscanf(x0,"%lf",&x);
			if(x<=1000&&x>=-1000) {
				k++;
				s+=x;
			} else {
				printf("ERROR: %s is not a legal number\n",x0);
			}
		} else {
			printf("ERROR: %s is not a legal number\n",x0);
		}
		i++;
	}
	if(k==0) {
		printf("The average of 0 numbers is Undefined\n");
	} else {
		double y=s/k;
			if(k==1)
			printf("The average of %d number is %.2f\n",k,y);
		else
			printf("The average of %d numbers is %.2f\n",k,y);
	}
	return 0;
}

注*:正则的代码如果运行不了是因为GCC版本太低了,需要至少4.9+

发布了19 篇原创文章 · 获赞 15 · 访问量 2465

猜你喜欢

转载自blog.csdn.net/qq_41829380/article/details/104317387
今日推荐