2019.2.19更新:感觉自己又变菜了,写这题花了40min(/颤抖),坑点如下
- 小数部分必须小于等于2位,比如0.001是不行的
- 最后一个测试点应该是有恰好为1000的测试数据。
- printf string的方法
printf("ERROR: %s is not a legal number\n", str.c_str());
更新代码:
#include<bits/stdc++.h>
using namespace std;
double val;
bool checkValid(string str) {
int neg = 0, dot = 0, dotLength = 0;
int integerPart = 0, decimalPart = 0;
for(int i = 0; i<str.length(); i++) {
if(i == 0 && str[i] == '-') {
neg = 1;
}else if(str[i]>='0' && str[i]<='9') {
if(dot) {
decimalPart = decimalPart*10+str[i]-'0';
} else {
integerPart = integerPart*10+str[i]-'0';
}
} else if(str[i] == '.') {
dotLength = str.length()-i-1;
if(dot || dotLength>2) {
return false;
} else {
dot++;
}
} else {
return false;
}
}
if(integerPart>1000) return false;
else if(integerPart == 1000 && decimalPart != 0) {
return false;
}
val = integerPart + decimalPart*1.0/pow(10, dotLength);
if(neg) val = -val;
return true;
}
int main() {
//freopen("in.txt", "r", stdin);
int N, validCount = 0;
cin >> N;
double sum = 0;
for(int i = 0; i<N; i++) {
string str;
cin >> str;
if(checkValid(str)) {
validCount++;
sum += val;
} else {
printf("ERROR: %s is not a legal number\n", str.c_str());
}
}
if(!validCount) {
printf("The average of 0 numbers is Undefined\n");
} else if(validCount == 1) {
printf("The average of 1 number is %.2f\n", sum);
} else {
printf("The average of %d numbers is %.2f\n", validCount, sum/validCount);
}
return 0;
}
之前思路没理清,WA哭,过了好久再写终于A了。。
#include<iostream>
#include<cstdio>
#include<string>
#include<cmath>
using namespace std;
int cnt;
double sum;
void solve(string str){
double num = 0, dotcnt = 0, dotnum = 0;
bool neg = false, dot = false;
for(int i = 0; i<str.length(); i++){
char ch = str[i];
if(ch>='0' && ch<='9'){
if(dot){
dotcnt++;
dotnum = dotnum*10+ch-'0';
}
else {
num = num*10+ch-'0';
}
}
else if(ch == '.'){
if(dot) {
cout << "ERROR: " << str << " is not a legal number\n";
return ;
}
else dot = true;
}
else if(ch == '-'){
if(neg) {
cout << "ERROR: " << str << " is not a legal number\n";
return ;
}
else neg = true;
}
else {
cout << "ERROR: " << str << " is not a legal number\n";
return ;
}
}
double tot = num + dotnum/pow(10, dotcnt);
if(fabs(tot) > 1000 || dotcnt > 2) {
cout << "ERROR: " << str << " is not a legal number\n";
return ;
}
cnt++;
if(neg) tot = -tot;
sum += tot;
}
int main(){
//freopen("in.txt", "r", stdin);
int n;
string str;
cin >> n;
for(int i = 0; i<n; i++){
cin >> str;
solve(str);
}
if(cnt == 0) cout<<"The average of 0 numbers is Undefined\n";
else if(cnt == 1) printf("The average of %d number is %.2f\n", cnt, sum/cnt);
else printf("The average of %d numbers is %.2f\n", cnt, sum/cnt);
return 0;
}