本文共 975 字,大约阅读时间需要 3 分钟。
#include#include #include #include #include using namespace std;//sscanf() – 从一个字符串中读进与指定格式相符的数据//sprintf() – 字符串格式化命令,主要功能是把格式化的数据写入某个字符串中。int main() { int n, cnt = 0; double sum = 0, t; char a[50], b[50]; cin >> n; for (int i = 0; i < n; i++) { cin >> a; sscanf(a, "%lf", &t);//从字符串中读出 sprintf(b, "%.2lf", t);//写入字符串 int flag = 0; for (int j = 0; j < strlen(a); j++) { if(a[j] != b[j]) flag = 1; } if(flag || t < -1000 || t > 1000) { printf("ERROR: %s is not a legal number\n", a); continue; }else{ sum += t; cnt++; } } if(cnt == 0) cout << "The average of 0 numbers is Undefined\n"; else if(cnt == 1) printf("The average of 1 number is %.2lf\n", sum); else printf("The average of %d numbers is %.2lf\n", cnt, sum / cnt); return 0;}
转载地址:http://scvix.baihongyu.com/