https://pintia.cn/problem-sets/994805260223102976/problems/994805272659214336
主要用的sscanf和sprintf函数
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int main(){
char a[50], b[50];
int n, cnt = 0;
double tmp, sum = 0.0;
cin >> n;
for(int i = 0; i < n; i++){
scanf("%s", &a);
sscanf(a, "%lf", &tmp);
sprintf(b, "%.2f", tmp);
int flag = 0;
for(int j = 0; j < strlen(a); j++)
if(a[j] != b[j]) flag = 1;
if(flag || tmp < -1000 || tmp > 1000){
printf("ERROR: %s is not a legal number\n", a);
continue;
}
sum += tmp;
cnt++;
}
if(cnt == 1)
printf("The average of 1 number is %.2f", sum);
else if(cnt > 1)
printf("The average of %d numbers is %.2f", cnt, sum / cnt);
else
printf("The average of 0 numbers is Undefined");
return 0;
}


本文介绍了一个利用sscanf和sprintf函数进行数值合法性检查及格式转换的C++程序实例。该程序能够读取一系列输入字符串,将其转换为浮点数,并检查其是否合法;对于合法的数值,程序将计算其平均值并输出。此实例适用于了解基本的输入输出流操作及数值处理。

被折叠的 条评论
为什么被折叠?



