气抖冷。。一个20分的题目卡了我半个多小时才搞出来。这是一道很有PAT味道的题目,小坑多得很呐~
坑1 :最后一个测试点中有-1000或者1000的测试,记得这个是***左闭右闭区间***!
坑2 :倒数第二个测试点中有关于单个数据平均值的情况,如果只有一个有效数据记得输出“number”而不是“numbers”
这是我的代码:(能AC 但完全是自己硬造的,没必要,建议看下文的精简版)
//
// Created by 曾仕邦 on 2021/8/21.
//
#include "bits/stdc++.h"
using namespace std;
bool Check(string s){
if(s[0]=='-') s.erase(s.begin());
if (s == "1000"||s == "1000.0" || s=="1000.00"||s=="-1000"||s=="-1000.0"||s=="-1000.00") return true;
int index = 0;bool flag= false;
for (int i = 0; i < s.length(); ++i) {
if (flag && s[i]=='.' && index != i) return false;
if (s[i] == '.') {index = i;flag = true;}
if ((s[i]<'0'||s[i]>'9')&&s[i]!='.')
return false;
}
if (index>3||s.length()-index>3) {
return false;}
return true;
}
double deal(string s){
double ans = 0;
bool flag = false;int index = 0;
if (s[0] == '-'){s.erase(s.begin());flag = true;}
for (int i = 0; i < s.length(); ++i) if (s[i] == '.') index = i;
double pow1 = 1, pow2 = 0.1;
if (index) {
for (int i = index - 1; i >= 0; --i) {
ans += pow1 * (s[i] - '0');
pow1 *= 10;
}
for (int i = index + 1; i < s.length(); ++i) {
ans += pow2 * (s[i] - '0');
pow2 /= 10;
}
}else{
for (int i = s.length()-1; i >= 0 ; --i) {
ans += pow1 * (s[i] - '0');
pow1 *= 10;
}
}
if (flag) ans = -ans;
return ans;
}
int main(){
int n;cin>>n;double avg = 0,count = 0;
for (int i = 0; i < n; ++i) {
string s;cin>>s;
if (Check(s)){
//cout<<deal(s)<<endl;
avg += deal(s);
count++;
}else{
cout<<"ERROR: "+s+" is not a legal number"<<endl;
}
}
if (count)
if (count==1) printf("The average of %d number is %.2f",(int)count,avg/count);
else printf("The average of %d numbers is %.2f",(int)count,avg/count);
else
cout<<"The average of 0 numbers is Undefined";
}
后面我看了y总的课之后。。。。。。。觉得自己写的是些啥啊,其中可以学习的地方
- 对于这种题目其实C++有个api叫stof,可以把字符串转成实数(要注意写try,而且如果夹杂了其他东西这个函数只会把前面的几个char转成实数,所以要判断是不是所有的字母都用上了)
- 字符串里找小数点直接用int pos = s.find(’.’);就好了,并不用自己遍历。
y总代码:
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int cnt = 0;
double sum = 0;
while (n -- )
{
string num;
cin >> num;
double x;
bool success = true;
try
{
size_t idx;
x = stof(num, &idx);
if (idx < num.size()) success = false;
}
catch(...)
{
success = false;
}
if (x < -1000 || x > 1000) success = false;
int k = num.find('.');
if (k != -1 && num.size() - k > 3) success = false;
if (success) cnt ++, sum += x;
else printf("ERROR: %s is not a legal number\n", num.c_str());
}
if (cnt > 1) printf("The average of %d numbers is %.2lf\n", cnt, sum / cnt);
else if (cnt == 1) printf("The average of 1 number is %.2lf\n", sum);
else puts("The average of 0 numbers is Undefined");
return 0;
}
作者:yxc
链接:https://www.acwing.com/activity/content/code/content/323460/
来源:AcWing
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。