题解 | #浮点数加法#
浮点数加法
http://www.nowcoder.com/practice/ddec753f446e4ba4944e35378ba635c8
题号:KY79 本体建立在浮点数的处理之上
将加法分为浮点数和小数两部分
- 对于浮点数,采用左对齐的方式,向整数部分传递一个进位,结果保存在较长的浮点数中
- 对于整数,采用右对齐,结果保存在大数中
需要特别注意的是 当两个整数长度不一致时,可能会有剩余的进位需要处理
#include <cstdio>
#include <string>
#include <iostream>
#include <iostream>
using namespace std;
int main(void){
string a, b;
while(getline(cin, a)){
getline(cin, b);
int cin = 0;
int res;
// calculate decimal
int idx_oa = a.find("."), idx_ob = b.find(".");
int len_oa = a.size() - idx_oa, len_ob = b.size() - idx_ob;
string de_oa = a.substr(idx_oa+1, len_oa);
string de_ob = b.substr(idx_ob+1, len_ob);
if(len_oa < len_ob)
swap(de_oa, de_ob);
cin = 0;
for(int i=de_ob.size()-1; i>=0; i--){
int oa = de_oa[i] - '0', ob = de_ob[i] - '0';
// printf("oa = %d, ob = %d\n", oa, ob);
if(oa + ob + cin > 9){
res = (oa + ob + cin) - 10;
cin = 1;
// printf("res = %d\n", res);
}else{
res = oa + ob + cin;
cin = 0;
}
de_oa[i] = res + '0';
}
// cout<<"decimal result"<<de_oa<<" Cin="<<cin<<endl;
// calculate inter
string int_oa = a.substr(0, idx_oa), int_ob = b.substr(0, idx_ob);
if(idx_oa < idx_ob)
swap(int_oa, int_ob);
int i, k;
for(i=int_oa.size()-1, k = int_ob.size()-1; i>=0&&k>=0; i--, k--){
int oa = int_oa[i] - '0', ob = int_ob[k] - '0';
// printf("oa = %d, ob = %d\n", oa, ob);
if(oa + ob + cin > 9){
res = (oa + ob + cin) - 10;
cin = 1;
// printf("res = %d\n", res);
}else{
res = oa + ob + cin;
cin = 0;
}
int_oa[i] = res + '0';
}
if(k < 0){
while(i>=0){
int oa = int_oa[i] - '0';
if(oa + cin > 9){
int_oa[i] = (oa+cin)-10 + '0';
cin = 1;
}else{
int_oa[i] = (oa+cin) + '0';
break;
}
}
}
cout<<int_oa<<"."<<de_oa<<endl;
}
return 0;
}