晚上好🌙🌙🌙
本答案参考ChatGPT-3.5
问题分析:
主要问题在于向个位偶数四舍五入的处理,需要注意0.a2=0.5时的特殊处理方式,即a1变为距离a1.a2最近的偶数并丢弃小数部分。出错原因主要在于没有考虑到这种特殊情况,或者在转换数字时出现了精度误差导致判断错误。常见的解决方法有以下几种:
解决方案:
- 直接根据题目规则计算四舍五入后的金额,比较与原金额的大小。这种方法需要注意0.a2=0.5时a1变为距离a1.a2最近的偶数的特殊规则。
示例代码:
#include <iostream>
using namespace std;
int main(){
int a1, a2;
cin>>a1>>a2;
int sum = a1 + ((a2>50||(a2==50&&a1%2==1))?1:0);
if(sum>a1) cout<<sum-a1<<" Happy birthday to MFGG"<<endl;
else if(sum<a1) cout<<a1-sum<<" Happy birthday to YXGG"<<endl;
else cout<<"PLMM"<<endl;
return 0;
}
时间复杂度:O(1)
空间复杂度:O(1)
- 先将a2保留1位小数后四舍五入,再根据规则计算四舍五入后的金额进行比较。这种方法是在有精度误差的情况下的一种解决方案。
示例代码:
#include <iostream>
using namespace std;
int main(){
int a1, a21, a22;
cin>>a1>>a21;
double a2 = a21 / 10.0;
a22 = int((a2 + 0.05) * 10 + 0.5) % 10;
a2 = int(a2 * 10 + 0.5) / 10.0;
int sum = a1 + ((a22>5||(a22==5&&a2>=0.5))?1:0);
if(sum>a1) cout<<sum-a1<<" Happy birthday to MFGG"<<endl;
else if(sum<a1) cout<<a1-sum<<" Happy birthday to YXGG"<<endl;
else cout<<"PLMM"<<endl;
return 0;
}
时间复杂度:O(1)
空间复杂度:O(1)
- 可以使用string来代替double类型以避免精度误差导致的错误。
示例代码:
#include <iostream>
#include <string>
using namespace std;
string add(string s1,string s2){
string res="";
int carry=0;//进位标志
for(int i=s1.size()-1;i>=0;i--){
int sum=s1[i]-'0'+s2[i]-'0'+carry;
res+=sum%10+'0';
carry=sum/10;
}
if(carry==1) res+='1';//若有进位,则再在末尾添1
reverse(res.begin(),res.end());
return res;
}
int main(){
int a1;
string a2, s="5", t="10";
cin>>a1>>a2;
int point = a2.length() - 1;
for(int i=1; i<=1+point; i++) t += '0'; // 10^{point+1}
for(int i=1; i<=point; i++) s += '0'; // 0.5 * 10^{point}
if(a2.length() == point){
a2 += '0'; //在最后加个0方便后面计算
point++;
}
if(a2[point]<'5'){
a2 = a2.substr(0, point);
}else if(a2[point]>'5'){
a2 = add(a2.substr(0, point), s).substr(0, point);
}else{
if((a2[point-1]-'0')%2==0){
a2 = a2.substr(0, point);
}else{
a2 = add(a2.substr(0, point), s).substr(0, point);
}
}
cout<<(a1+stoi(a2+t.substr(point+1))>a1?a1+stoi(a2+t.substr(point+1))-a1:(a1+stoi(a2+t.substr(point+1))==a1?"PLMM":a1-stoi(a2+t.substr(point+1)))<<(a1+stoi(a2+t.substr(point+1))>a1?" Happy birthday to MFGG":" Happy birthday to YXGG")<<endl;
return 0;
}
时间复杂度:O(n)
空间复杂度:O(n)