巧用sscanf和sprintf:
#include<iostream>
#include<algorithm>
#include<cstring>
#include<string>
#include<cstdio>
#include<cctype>
#include<cmath>
#include<vector>
#include<queue>
#include<set>
#include<map>
#include<stack>
#include<sstream>
#define mm(a,x) memset(a,x,sizeof(a))
#define maxn 100005
using namespace std;
typedef long long ll;
const int INF=0x3f3f3f3f;
int main()
{
int n; cin>>n;
int k=0;double sum=0,num;
while(n--){
getchar();
char s[maxn];char s1[maxn];
cin>>s;
sscanf(s,"%lf",&num);
sprintf(s1,"%.2f",num);
bool ans=true;
for(int i=0;i<strlen(s);i++)
{
if(s[i]!=s1[i])
ans=false;
}
if(ans&&num>=-1000&&num<=1000){
k++;
sum+=num;
}else{
cout<<"ERROR: "<<s<<" is not a legal number\n";
}
}
if(!k) cout<<"The average of 0 numbers is Undefined\n";
else if(k==1) printf("The average of 1 number is %.2f\n",sum);
else printf("The average of %d numbers is %.2f\n",k,sum/k);
}
- 将输入先接收到字符串中
- 依序检查是否有非数字,注意负号和小数点合法,其他非数字出现即不合法
- 均为数字后,检查是否有小数点
- 无小数点则为整数
- 有小数点要分别检查是否有多个小数点(s.find_first_of(’.’) != s.find_last_of(’.’))和小数位数是否超过2(s.length()-s.find(’.’) > 3)
- 以上去掉格式不合法数字后,转化为double型,看是否在[-1000,1000]范围内,不在亦不合法
- 输出时注意区分 0、1(number单数) 及其他
#include<iostream>
using namespace std;
int main()
{
int n, num = 0;
cin >> n;
string s;
double data, sum = 0;
for (int i = 0; i < n; i++){
bool islegal = true;
cin >> s;
for (int j = 0; j < s.length(); j++){
if ((s[j]>'9' || s[j]<'0') && s[j]!='-' && s[j]!='.'){
cout << "ERROR: " << s << " is not a legal number\n";
islegal = false;
break;
}
}
if (islegal){
if (s.find('.') != string::npos){
if(s.find_first_of('.') != s.find_last_of('.') || s.length()-s.find('.') > 3){
cout << "ERROR: " << s << " is not a legal number\n";
continue;
}
}
data = stod(s);
if (data >= -1000 && data <= 1000){
sum += data;
num++;
}
else cout << "ERROR: " << s << " is not a legal number\n";
}
}
if (!num) cout << "The average of 0 numbers is Undefined";
else if (num == 1) printf("The average of 1 number is %.2f", num, sum);
else printf("The average of %d numbers is %.2f", num, sum/num);
return 0;
}