请大家为我讲构。

yaoyaohuanghuang 2003-10-21 12:04:42
我们知道数据里的各变量类型都有范围限制,在这里我想问大家如果有一个很长的数据相加或相减,能用一种方法诠释它的运作方式吗?谢谢。如用188887654342121+235690212345。
...全文
38 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
ZhangYv 2003-10-24
  • 打赏
  • 举报
回复
这是处理2进制的高精度加,减和乘法的C++程序,算法就是模拟手工计算,注意进位.
/* Prositive HighPricistion—Operation of baniry system */
#include <iostream.h>
#include <mem.h>
const int MAXSIZE = 20; //max length of the number
const int K = 2; //baniry system 在这里可以修改K进制的高精度
class hp{
int len; //length of number
int s[MAXSIZE]; //store high precistion number
public:
hp();
hp hp::operator = (hp C);
};
hp::hp()
{
len = 0;
memset(s, 0, MAXSIZE*sizeof(int));
}
istream &operator >> (istream &in, hp &HP)
{
char s[MAXSIZE];
int i;
cout << "Input Number = ";
cin >> s;
HP.len = strlen(s);
for (i = 0; i < HP.len; i++)
HP.s[i] = s[HP.len-i-1] - '0'; //change string to high precisition
return in;
}
ostream &operator << (ostream &out, hp &HP)
{
int i;
for (i = HP.len-1; i >= 0; i--)
cout << HP.s[i];
return out;
}
hp operator +(hp A, hp B)
{
int i, len;
hp C;
if (A.len > B.len)
len = A.len;
else
len = B.len; //get the bigger length of A,B
for (i = 0; i < len; i++){
C.s[i] += A.s[i] + B.s[i];
if (C.s[i] >= K){
C.s[i] -= K;
++C.s[i+1]; //add 1 to a higher position
}
}
if (C.s[len] > 0)
C.len = len+1;
else
C.len = len;
return C;
}
hp operator - (hp A, hp B) //different of the two HighPrecision Numbers
{
int len, i;
hp C;
if (A.len > B.len)
len = A.len;
else
len = B.len;C.len = 4;
for (i = 0; i < len; i++){
C.s[i] += A.s[i] - B.s[i];
if (C.s[i] < 0){
C.s[i] += K;
--C.s[i+1]; //subtract 1 to higher position
}
}
while (C.s[len-1] == 0 && len > 1)
--len;
C.len = len;
return C;
}
hp operator * (const hp &A, const hp &B)
{
int len, i, j;
hp C;
for (i = 0; i < A.len; i++)
for (j = 0; j < B.len; j++){
len = i+j;
C.s[len] += A.s[i] * B.s[j];
C.s[len+1] += C.s[len] / K;
C.s[len] %= K;
}
len = A.len + B.len + 1;
/*
the product of a number with i digits and a number with j digits
can only have at most i+j+1 digits
*/
while (len > 1 && C.s[len-1] == 0)
--len;
C.len = len;
return C;
}
hp hp::operator = (hp C)
{
int i;
len = C.len;
for (i = 0; i < MAXSIZE; i++)
s[i] = C.s[i];
return *this;
}
int main()
{
hp A, B, C;
cin >> A >> B;
C = A+B;
cout << A << ‘+’ << B << “ = “ << C << endl;
C = A-B;
cout << A << ‘-’ << B << “ = “ << C << endl;
C = A*B;
cout << A << '*' << B << " = " << C << endl;
return 0;
}
pxwzd123 2003-10-24
  • 打赏
  • 举报
回复

大数运算要借助数组,大数用数组表示,加上相应的转换即可以完成运算
frankzch 2003-10-21
  • 打赏
  • 举报
回复
简单的加减用数组存储数据的每一位就行了,注意进位

33,006

社区成员

发帖
与我相关
我的任务
社区描述
数据结构与算法相关内容讨论专区
社区管理员
  • 数据结构与算法社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧