PAT乙级1054 求平均值

#include <cstdio>
#include <cstring>
//写法不严谨,居然测试点全过了 
int main(){
	int n, count = 0;	//count是合法数字数量 
	double temp, legalSum = 0;	//legalSum是合法数字总和 
	char str[100];	//保存每个读取的字符串 
	scanf("%d", &n);
	for(int i = 0; i < n; i++){
		scanf("%s", str);
		int len = strlen(str), dotCount = 0;	//dotCount记录小数点的数量 
		bool isLegal = true;	//默认合法 
		if((str[0] > '9' || str[0] < '0') && str[0] != '-') isLegal = false;	//第一位只能是数字或者符号 
		int dotPosition = -1;	//记录小数点位置,判断精度是否符合要求 
		for(int j = 1; j < len; j++){
			if(str[j] > '9' || str[j] < '0'){	//只能是数字或者小数点,且小数点只能出现一次 
				if(str[j] == '.'){
					if(dotCount == 0) dotCount++, dotPosition = j;
					else isLegal = false;
				}else isLegal =false;
			}
		}
		if(dotPosition != -1 && len - dotPosition > 3) isLegal = false;	//用小数点位置判断精度 
		if(isLegal){
				sscanf(str, "%lf", &temp);
				if(temp >= -1000 && temp <= 1000){	//是否在规定范围内 
					count++;
					legalSum += temp;
				}
				else printf("ERROR: %s is not a legal number\n", str);
			}else printf("ERROR: %s is not a legal number\n", str);
	}
	if(count == 0) printf("The average of 0 numbers is Undefined");
	else if(count == 1) printf("The average of 1 number is %.2f", legalSum);
	else printf("The average of %d numbers is %.2f", count, legalSum / count);
	
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值