题意:给定一些字符串,判断是否是满足条件的浮点数,如果是则求其平均值,否则打印不是合法浮点数。
思路:主要是两个类似于函数的用法。
sscanf(a,"%lf",&temp);//按照指定的格式将a转化之后复制给temp,
sprintf(b,"%.2lf",temp);//按照指定的格式格式化temp后复制给b
代码:
#include<iostream>
#include<cstdio>
#include<string.h>
using namespace std;
int main() {
int n,cnt = 0, flag = 0;
char a[50], b[50];
double temp,sum = 0;
cin >> n;
for (int i = 0; i < n; i++) {
scanf("%s", a);
sscanf(a, "%lf", &temp);//按照指定格式读入字符串到temp
sprintf(b, "%.2lf", temp);//格式化字符串temp到b中
flag = 0;
for (int i = 0; i < strlen(a); i++) {
if (a[i] != b[i])flag = 1;
}
if (flag || temp < -1000 || temp > 1000) {
printf("ERROR: %s is not a legal number\n", a);
continue;
}
else {
cnt++;
sum += temp;
}
}
if (cnt == 0) {
printf("The average of 0 numbers is Undefined\n");
}
else {
if (cnt == 1)printf("The average of 1 number is %.2lf\n",sum/cnt);
else printf("The average of %d numbers is %.2lf\n", cnt, sum / cnt);
}
system("pause");
return 0;
}