【PAT乙级】1054 求平均值 (20 分)

在这里插入图片描述
题目地址

测试点 2:k==1 number没有s
测试点 3:12. 这种是合法的

#include<cstdio>
#include<iostream>
#include<string>
using namespace std;
int n;
string s;
bool check(string s)
{
	if( (s[0]=='+'||s[0]=='-') && s.size()==1) return false;
	if(s[0]=='+'||s[0]=='-') s=s.substr(1);
	int k=0,index=0;
	for(int i=0;i<s.size();i++)
	{
		if(s[i]=='.') k++,index=i+1;
		else if(s[i]<'0'||s[i]>'9') return false;
	}
	if(k>=2) return false;
	if(k==0) return true;
	if( (s.size()-index)>2 ) return false;
	return true;
}
int main(void)
{
	cin>>n;
	double sum=0;
	int cnt=0;
	bool flag=false;
	for(int i=0;i<n;i++)
	{
		cin>>s;
		if(check(s)) 
		{
			double temp=stod(s);
			if(temp>=-1000.0&&temp<=1000.0) sum+=temp,cnt++,flag=true;
            else printf("ERROR: %s is not a legal number\n",s.c_str());
		}
		else printf("ERROR: %s is not a legal number\n",s.c_str());
	}
	if(flag&&cnt!=1) printf("The average of %d numbers is %.2lf\n",cnt,sum/cnt);
	else if(flag) printf("The average of %d number is %.2lf\n",1,sum);
	else printf("The average of 0 numbers is Undefined");
	return 0;
}
#include<bits/stdc++.h> 
using namespace std;
int cnt,t;
double sum;
bool check(string s)
{
	string temp=s;
	int k=0;
	if(temp[0]=='-'||temp[0]=='+') temp=temp.substr(1);
	for(int i=0;i<temp.size();i++)
	{
		if(temp[i]=='.') k++;
		else if(temp[i]<'0'||temp[i]>'9') return false;
	}
	if(k>1) return false;
	if(k)
	{
		int l=temp.find('.');
		int len=temp.size()-l-1;
		if(len>2) return false;
	}
	double a=stod(s);
	if(a>=-1000.0&&a<=1000.0) return true;
	else return false;
}
int main(void)
{
	cin>>t;
	while(t--)
	{
		string s; cin>>s;
		if(check(s)) cnt++,sum+=stod(s);
		else printf("ERROR: %s is not a legal number\n",s.c_str());
	}
	if(cnt>1)  printf("The average of %d numbers is %.2lf",cnt,sum/cnt);
    else if(cnt==1) printf("The average of %d number is %.2lf",cnt,sum/cnt);
	else printf("The average of 0 numbers is Undefined");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值