写在前面

  • 实现思路
  • 字符数组存储输入数字
  • 通过​​sscanf​​​、​​sprintf​​ 处理读取字符串
  • ​cstdio​​头文件下
  • ​sscanf(a, "%lf", &real_num);​​​ : 将字符数组str中的内容以​​%lf​​​格式写到​​real_num​​中(从左至右)
  • ​sprintf(b, "%.2f",real_num);​​​ : 把​​real_num​​​以​​%.2f​​形式写到str字符数组中
  • 字符循环对比、浮点数范围判断
  • 题目较为简单,熟识​​sscanf / sprintf​​函数事半功倍。
  • 15分钟内可a题

测试用例

input:
7
5 -3.2 aaa 9999 2.3.4 7.123 2.35
output:
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

input:
2
aaa -9999
output:
ERROR: aaa is not a legal number
ERROR: -9999 is not a legal number
The average of 0

ac代码

#include <iostream>
#include <cstdio>
#include <string.h>
using namespace std;
int main() {
int n, cnt = 0;
char a[50], b[50];
double real_num = 0.0, sum = 0.0;

scanf("%d", &n);
for(int i = 0; i < n; i++) {
scanf("%s", a);
sscanf(a, "%lf", &real_num);
sprintf(b, "%.2f",real_num);

int flag = 0;
for(int j = 0; j < strlen(a); j++)
if(a[j] != b[j]) flag = 1;
if(flag || real_num < -1000 || real_num > 1000) {
printf("ERROR: %s is not a legal number\n", a);
continue;
} else {
sum += real_num;
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;
}

知识点小结

  • sprintf、sscanf函数熟练使用
// Write formatted data to string
int sprintf ( char * str, const char * format, ... );

// Read formatted data from string
int sscanf ( char * str, const char * format, ...);
  • ​sprintf​​简单示例
/* sprintf example */
#include <stdio.h>

int main ()
{
char buffer [50];
int n, a=5, b=3;
n=sprintf (buffer, "%d plus %d is %d", a, b, a+b);
printf ("[%s] is a %d char long string\n",buffer,n);
return 0;
}
Output:
[5 plus 3 is 8] is a 13 char long
  • ​sscanf​​简单示例
/* sscanf example */
#include <stdio.h>

int main ()
{
char sentence []="Rudolph is 12 years old";
char str [20];
int i;

sscanf (sentence,"%s %*s %d",str,&i);
printf ("%s -> %d\n",str,i);

return 0;
}
Output:
Rudolph -> 12