题解 | #浮点数加法#人人都懂的版本
浮点数加法
https://www.nowcoder.com/practice/ddec753f446e4ba4944e35378ba635c8?tpId=61&tqId=29551&tPage=3&ru=/kaoyan/retest/1002&qru=/ta/pku-kaoyan/question-ranking
#include <algorithm> #include <iostream> using namespace std; int cf=0; string plusf(string x,string y){ int len1=x.size(),len2=y.size(); if(len1<len2){ for(int it=len1;it<len2;it++){ x.insert(x.size(), "0"); } len1=len2; } else if(len2<len1){ for(int it=len2;it<len1;it++){ y.insert(y.size(), "0"); } len2=len1; } //vector<char> resf;resf.clear(); for(int j=len2-1;j>=0;j--){ int m=x[j]-'0',n=y[j]-'0'; int t=(m+n+cf)/10; x[j]=(m+n+cf)%10+'0'; if(t!=0) cf=1; else cf=0; } return x; } string pluse(string x,string y){ int len1=x.size(),len2=y.size(); if(len1<len2){ for(int it=len1;it<len2;it++){ x.insert(0, "0"); } len1=len2; } else if(len2<len1){ for(int it=len2;it<len1;it++){ y.insert(0, "0"); } len2=len1; } //vector<char> rese;rese.clear(); for(int j=len2-1;j>=0;--j){ int m=x[j]-'0',n=y[j]-'0'; int t=(m+n+cf)/10; x[j]=(m+n+cf)%10+'0'; if(t!=0) cf=1; else cf=0; } if(cf==1) x.insert(0,"1"); return x; } int main() { string a,b; cin>>a>>b; int d1=a.find('.'),d2=b.find('.'); int l1=a.size(),l2=b.size(); string e1=a.substr(0,d1),f1=a.substr(d1+1,l1-1); string e2=b.substr(0,d2),f2=b.substr(d2+1,l2-1); string resf=plusf(f1, f2); string rese=pluse(e1, e2); cout<<rese<<"."<<resf<<endl; return 0; } // 64 位输出请用 printf("%lld")