c++高精度浮点数加法
时间: 2023-11-30 08:42:41 浏览: 171
高精度头文件(带小数)(C++)
以下是C++实现高精度浮点数加法的示例代码:
```c++
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1e5 + 10;
struct Bignum
{
int len, s[N];
Bignum()
{
memset(s, 0, sizeof(s));
len = 1;
}
Bignum(int num)
{
*this = num;
}
Bignum(const char* num)
{
*this = num;
}
Bignum operator = (int num)
{
char s[N];
sprintf(s, "%d", num);
*this = s;
return *this;
}
Bignum operator = (const char* num)
{
memset(s, 0, sizeof(s));
len = strlen(num);
for (int i = 0; i < len; i++) s[i] = num[len - i - 1] - '0';
return *this;
}
string str() const
{
string res = "";
for (int i = 0; i < len; i++) res = (char)(s[i] + '0') + res;
if (res == "") res = "0";
return res;
}
Bignum operator + (const Bignum& b) const
{
Bignum c;
c.len = 0;
for (int i = 0, g = 0; g || i < max(len, b.len); i++)
{
int x = g;
if (i < len) x += s[i];
if (i < b.len) x += b.s[i];
c.s[c.len++] = x % 10;
g = x / 10;
}
return c;
}
};
ostream& operator << (ostream& out, const Bignum& x)
{
out << x.str();
return out;
}
istream& operator >> (istream& in, Bignum& x)
{
string s;
in >> s;
x = s.c_str();
return in;
}
int main()
{
Bignum a, b;
cin >> a >> b;
cout << a + b << endl;
return 0;
}
```
阅读全文