要注意的地方:
1.输入为字符串,要把它倒置存储到数组中,字符串的0为最高位。同样,输出结果数组时,也应该倒序输出。
2.注意for循环的约束条件为i<a.lenth()||i<b.lenth()
3.若循环完后,进位!=0,说明比原输入的两个数组长度大,要加上进位的1位。
代码:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<math.h>
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main() {
string a, b;
while (cin >> a >> b) {
int c[1001] = { 0 };
int d[1001] = {0};
int sum[1002] = {0};
int t = a.length()-1;
int s = b.length()-1 ;
for (int i = 0; i < a.length(); i++) {
c[i] = (a[t--]-'0');
}
for (int i = 0; i < b.length(); i++) {
d[i] = (b[s--]-'0');
}
int carry = 0;
int i = 0;
for (i; i < a.length() || i < b.length(); i++) {
sum[i] = (c[i] + d[i]+carry) % 10;
carry= (c[i] + d[i] + carry) /10;
}
if (carry != 0) {
sum[i] = carry;
for (int t = i; t >= 0; t--) {
cout << sum[t];
}
}
else {
for (int t = i-1; t >= 0; t--) {
cout << sum[t];
}
}
cout << endl;
}
return 0;
}
浮点数加法要注意的比较多,使用一个结构体存储小数整数以及各自位数更加方便。先遍历得到整数位数,然后小数和整数是相反的,同时要注意如果小数最高位为0,小数位数要减一。最后要判断是否有小数部分,若没有不输出.
参考:
https://blog.youkuaiyun.com/Rhao999/article/details/104236678