核心语句:
double x;
char s[100],ss[100];
sscanf(s, "%lf", &x); //将这一字符串输出为一个浮点数x中
sprintf(ss, "%.2f", x); //将这一浮点数输出为一个有两位小数的字符串ss中
AC代码:
#include<bits/stdc++.h>
using namespace std;
double x;
char s[100],ss[100];
bool isNum()
{
sscanf(s, "%lf", &x); //将这一字符串输出为一个浮点数x中
sprintf(ss, "%.2f", x); //将这一浮点数输出为一个有两位小数的字符串ss中
for(int i=0;i<strlen(s);i++) //经过对s进行转化为浮点数x再转化为符合规定的浮点数字符串ss之后,将s与ss对比,对比长度为s的长度,一旦有不同,则返回false
if(s[i]!=ss[i])
return false;
if(abs(x)>1000)
return false;
return true;
}
int main()
{
int N;
scanf("%d",&N);
double ans=0;
int num=0;
for(int i=0;i<N;i++)
{
scanf("%s", s);
if(isNum())
{
num++;
ans+=x;
}
else
printf("ERROR: %s is not a legal number\n", s);
}
if(num==0)
printf("The average of 0 numbers is Undefined");
else if(num==1)
printf("The average of 1 number is %.2f",ans);//number不加s
else
printf("The average of %d numbers is %.2f",num,ans/num);
return 0;
}