首页 > 其他 > 详细

PTA乙级 (*1054 求平均值 (20分))

时间:2020-01-22 23:56:37      阅读:181      评论:0      收藏:0      [点我收藏+]

1054 求平均值 (20分)

https://pintia.cn/problem-sets/994805260223102976/problems/994805272659214336

#include <cstdio>
#include <cstring>
#include <string>
#include <iostream>
#include <cmath>
#include <algorithm>
#include <iomanip>
using namespace std;
bool check(string &str)
{
	bool flag=false;
	int i=0,a=0,b=0;
	if(str[i]==‘-‘) i++;
	for(;i<str.size();i++)
	{
		if((!isdigit(str[i]))&&(str[i]!=‘.‘)) return false;
		if(str[i]==‘.‘) 
		{
			a++;
			flag=true;
			continue;
		}
		if(flag) b++;
	}
	if(a>1||b>2||stod(str)>1000||stod(str)< -1000) return false;
	else return true;
}
int main()
{
	int n,count=0;
	string str;
	double sum=0;
	cin>>n;
	for(int i=0;i<n;i++) 
	{
		cin>>str;
		if(!check(str)) cout<<"ERROR: "<<str<<" is not a legal number\n";  
		else if(check(str)){
			count++;
			sum+=stod(str);
		}
	}
	if(count==0) cout<<"The average of 0 numbers is Undefined\n";
	else if(count==1) cout<<"The average of 1 number is "<<fixed<<setprecision(2)<<sum<<endl;
	else printf("The average of %d numbers is %.2f\n",count,sum/count);
	return 0;
}

PTA乙级 (*1054 求平均值 (20分))

原文:https://www.cnblogs.com/jianqiao123/p/12229957.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!