B1054 求平均值 (20 分 | 字符串处理,附详细注释,逻辑分析)
作者:互联网
写在前面
- 思路分析
- 字符数组存储读入数据,
char a[50], b[50];
- 字符串格式化读取、格式化写入函数
- sscanf() – 从1个字符串中读进与指定格式相符的数据
- sprintf() – 字符串格式化命令,主要功能是把格式化的数据写入某个字符串
- 字符数组存储读入数据,
- 问题点
- 合法区间、合法实数校验,
[−1000,1000]
- 输出坑,
numbers / numbers
The average of K numbers is Y,其中 K 是合法输入的个数,Y 是它们的平均值,精确到小数点后 2 位
如果平均值无法计算,则用 Undefined 替换 Y
如果 K 为 1,则输出 The average of 1 number is Y
- 合法区间、合法实数校验,
- 题目简单,10分钟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 numbers is Undefined
ac代码
#include <iostream>
#include <cstdio>
#include <string.h>
using namespace std;
int main()
{
int n, cnt = 0;
cin >> n;
char a[50],b[50];
double tmp, sum = 0.0;
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;
}
else
{
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
- 格式化字符串输入
int sscanf ( char * str, const char * format, ...);
-
/* 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
-
sprintf
- 字串格式化命令,主要功能是把格式化的数据写入某个字符串
int sprintf ( char * str, const char * format, ... );
返回值:字符串长度(strlen)
-
/* 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 string
标签:20,int,number,legal,B1054,char,numbers,ERROR,字符串 来源: https://blog.csdn.net/qq_24452475/article/details/100185336