1054. 求平均值

本題的基本要求非常簡單:給定N個實數,計算它們的平均值。但複雜的是有些輸入數據可能是非法的。一個“合法”的輸入是[-1000,1000]區間內的實數,並且最多精確到小數點後2位。當你計算平均值的時候,不能把那些非法的數據算在內。

輸入格式:

輸入第一行給出正整數N(<=100)。隨後一行給出N個實數,數字間以一個空格分隔。

輸出格式:

對每個非法輸入,在一行中輸出“ERROR: X is not a legal number”,其中X是輸入。最後在一行中輸出結果:“The average of K numbers is Y”,其中K是合法輸入的個數,Y是它們的平均值,精確到小數點後2位。如果平均值無法計算,則用“Undefined”替換Y。如果K爲1,則輸出“The average of 1 number is Y”。

輸入樣例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

=========================================================================================
不怎麼難隨便去別人那搜吧……
但是非常玄學的是第三個測試點就是過不了,也注意了number不加s的事情了。【按照網上的說法,就是測試
K=1的情況】
經過測試,我能夠確定那個樣例的確進了k=1的情況。【將輸出改爲一個死循環,只有那個測試點超時】
後來我在想,是不是我的判斷函數有問題,於是搜索了一下別人的AC代碼,摘了一個替換我的函數,還是第三
個測試點WA,其餘通過……
至今原因未明,求大佬指正是哪裏出錯了。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <iomanip>
#include <cmath>
#include <algorithm>
#include <string>
#include <cctype>
#include <sstream>
#include <map>
#include <set>
#include <list>
#include <vector>
#include <queue>
#include <stack>
#define MAXN 100005
#define INF 0x7f
using namespace std;

bool judge(string str);

int main()
{
	int n,i,j,len,num=0;
	double k,sum=0;
	string temp;
	stringstream ss;
	cin>>n;
	int arr[105]={0};
	for(i=0;i<n;i++)
	{
		k = 0;
		temp.clear();
		ss.clear();
		cin>>temp;
		if(judge(temp) == true)
		{
			ss<<temp;
			ss>>k;
			if(k>1000.0 || k<-1000.0)
			{
				cout<<"ERROR: "<<k<<" is not a legal number"<<endl;
			}
			else
			{
				sum += k;
				num++;
			}
		}
		else
			cout<<"ERROR: "<<temp<<" is not a legal number"<<endl;
	}
	if(num == 0)
	{
		cout<<"The average of 0 numbers is Undefined"<<endl;
	}
	else if(num == 1)
	{
		cout<<"The average of 1 number is "<<fixed<<setprecision(2)<<sum<<endl;
	}
	else
	{
		sum /= (double)num;
		cout<<"The average of "<<num<<" numbers is "<<fixed<<setprecision(2)<<sum<<endl;
	}
	return 0;
}

bool judge(string str)
{
	int i,len,flag=0;
	len = str.size();
	for(i=0;i<len;i++)
	{
		if(str[i]<'0' || str[i]>'9')
		{
			if(str[i]=='-')
            {
                if(i != 0)
                    return false;
            }
            else if(str[i]=='.' && i==0)
                return false;
            else if(str[i]=='.' && i==1 && str[0]=='-')
                return false;
			else if(str[i]=='.' && flag==0)
			{
				flag = 1;
                if(len-i > 3)
                    return false;
			}
			else
				return false;
		}
	}
	return true;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章