1. 程式人生 > >1054 求平均值 (20 分)

1054 求平均值 (20 分)

輸入格式:

輸入第一行給出正整數 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

 感覺本題的情況複雜較多,容易遺漏,樣例的給出給我們提供了幾種不合法的情況。但我最初的想法是找合法的,只要是判定是不是合法,就可以將不合法的輸出,但是問題在於我找不到一種可以判定合法的方式,然後就去網上瀏覽了一下,發現網上也沒有這種思路的解法,只好放棄,而且幾乎都是對每種情況進行分析,除了python的解題程式碼較為簡潔外,其餘的c++的解法似乎沒有少於50行的。下面是兩種比較短的程式碼

c++

#include <stdio.h>
#include <stdlib.h>
char a[120];//儲存一個合法的數字
int checkvalid(void)
{
	int i=1,point_count=0;
	if( !(a[0] == '-' || a[0] >='0' && a[0] <= '9' || a[0] == '+' || a[0] =='.')) //第一位非法
		return 0;
	if(a[0] == '0')
	{
		if( !(a[1] == '.' || a[1] =='\0')) //第一位為0
			return 0;
	}
	if(a[0] == '.')
	{
		if( !(a[1] =='\0' || a[2] == '\0') )
			return 0;
		point_count ++;
	}
	if(a[0] == '-' || a[0] == '+' )  //負數或加了正號的正數的第一位為0
	{
		if(a[1] == '0')
		{
			if( ! (a[2] == '.' || a[2] == '\0'))
				return 0;
		}
		if(!(a[1] >='0' && a[1] <='9' || a[1] == '.'))//符號的下一位必須是數字或小數點
			return 0;
	}
	while(a[i] != '\0')  //第2位開始
	{
		if(a[i] =='.')
		{
			point_count++;
			if(point_count == 2) //至多一個小數點
				return 0;
			if(   !(a[i-1] <='9' && a[i-1] >= '0' || a[i-1] =='+' || a[i-1] =='-') ) //小數點左必是數字或符號
				return 0;
			if( !(a[i+2] == '\0' || a[i+3] == '\0') ) //小數點後2至3位必有一個為字串終點
				return 0;
		}
		if( !(a[i] >='0' && a[i] <='9' || a[i] =='.') ) //必須都是合法的數字或小數點
			return 0;
		i++;
	}
	if(! (atof(a) <= 1000.00 && atof(a) >=-1000.00) )  //越界
		return 0;
	return 1;
}
int main()
{
	int N,i,count=0;
	double sum=0;
	scanf("%d",&N);
	for(i=0;i<N;i++)
	{
		scanf("%s",a);
    if(checkvalid())
    {
			sum += atof(a);
			count++;
		}
		else
		{
			printf("ERROR: %s is not a legal number\n",a);
		}
	}
	if(count != 0)
	{
		if(count != 1)
			printf("The average of %d numbers is %.2lf\n",count,sum / count);
		else
			printf("The average of 1 number is %.2lf\n",sum );
	}
	else
		printf("The average of 0 numbers is Undefined\n");
}

python


n = int(input())
a = input().split()
error = []
right = []
for i in a:
    try:
        k = int(i)
        if k<-1000 or k>1000:
            error.append(i)
        else:
            right.append(k)
    except:
        try:
            k = float(i)
            if k<-1000 or k>1000:
                error.append(i)
            elif len(i)-i.index('.')-1>2:
                error.append(i)
            else:
                right.append(k)
        except:
            error.append(i)
for i in range(len(error)):
    print("%s%s%s"%("ERROR: ",error[i]," is not a legal number"))
if len(right)==0:
    print("%s%d%s"%("The average of ",len(right)," numbers is Undefined"))
elif len(right)==1:
    print("%s%d%s%.2f"%("The average of ",len(right)," number is ",right[0]))
else:
    b = 0
    for i in right:
        b+=i
    b = b/len(right)
    print("%s%d%s%.2f"%("The average of ",len(right)," numbers is ",b,))