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
-
思路 1:
开始自己做(用stod()不断变来变去,判断),有个点一直过不去,现在也还没过去…- -!难受
不过从柳神那学到一招sscanf()和sprintf(): -
code 1:
#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;
}
-
TIPS 1:
sscanf(str, "%lf", &tmp);
:将str以浮点数形式写入tmp,若格式不符,不写入 -
TIPS 2:
sprintf(str, "%.2f", tmp);
:将tmp(浮点数形式)以.2f格式写入str,若tmp与.2f格式不匹配:如char tmp[]:输出0.00,但换成"%d"就输出 7405072不知道什么原理
这两个函数都只对char 数组有效:string要转化为char数组,即:str.c_str()
标签:tmp,PAT,ERROR,number,legal,A1108,2f,ori,Finding 来源: https://blog.csdn.net/qq_42347617/article/details/100545030