其他分享
首页 > 其他分享> > PAT A1108 Finding Average

PAT A1108 Finding Average

作者:互联网

PAT A1108 Finding Average

在这里插入图片描述

Sample Input 1:

7
5 -3.2 aaa 9999 2.3.4 7.123 2.35

Sample Output 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

Sample Input 2:

2
aaa -9999

Sample Output 2:

ERROR: aaa is not a legal number
ERROR: -9999 is not a legal number
The average of 0 numbers is Undefined
#include <iostream>
#include <stdio.h>
#include <cstring>
using namespace std;
bool cmp(char a[], char b[]){
	for(int i = 0; i < strlen(a); ++i){
		if(a[i] != b[i]) return false;
	}
	return true;
}
bool isRange(double x){
	return x < -1000 || x > 1000 ? false : true;
}
int main(){
	int n, cnt = 0;
	char ori[50], com[50];
	double tmp, sum = 0;
	scanf("%d", &n);
	for(int i = 0; i < n; ++i){
		scanf("%s", ori);
		sscanf(ori, "%lf", &tmp);	//!!!TIPS 1:将ori以浮点数形式写入tmp,若格式不符,不写入
		sprintf(com, "%.2f", tmp);	//!!!TIPS 2:将tmp(一定是从ori上取下的浮点数)以.2f的格式写入com 
		if(cmp(ori, com) && isRange(tmp)){
			sum += tmp;
			cnt++;
		}else printf("ERROR: %s is not a legal number\n", ori);
	}
	if(cnt > 1) printf("The average of %d numbers is %.2f", cnt, sum/cnt);
	else if(cnt == 1) printf("The average of 1 number is %.2f", sum);
	else printf("The average of 0 numbers is Undefined");
	return 0;
}

这两个函数都只对char 数组有效:string要转化为char数组,即:str.c_str()

标签:tmp,PAT,ERROR,number,legal,A1108,2f,ori,Finding
来源: https://blog.csdn.net/qq_42347617/article/details/100545030