问题描述
到目前为止,我有一个add,subtract和print函数以及一个初始化为数组的构造函数。由于某种原因,操作(+和 - )对我来说很有意义(我认为)所以我有点超越自我并且不太确定如何初始化一个大整数,我可以得到一些函数这样的帮助作为void assign(const bigint& A)或类似的东西?如果我的代码有问题,请告诉我。谢谢
So far I've got an add, subtract and print function as well as a constructor that initializes to zero the array. For some reason the operations(+ and -) made alot of sense to me(i think) so I kind of got ahead of my self and am not too sure how to initialize a big integer, could I get some help with a function such as void assign(const bigint & A) or something like that? Also if there is something already wrong with my code please tell me. Thanks
const int size=30; //just to make things easier, will change to something big later
class bigint
{
int digits[size];
public:
// initializes to zero
bigint()
{
for (int i = 0; i < size; i++)
digits[i] = 0;
}
// prints a big int
void print()
{
bigint B;
for (int i = size - 1; i >= 0; i--)
{
int dig = B.digits[i];
if (dig != 0)
std::cout << dig;
}
}
// subtracts a bigint(B) from another(A)
void subtract(bigint & A, bigint & B)
{
for (int i = 0, borrow = 0; i < size; i++)
{
if (borrow = ((A.digits[i] -= B.digits[i] + borrow) < 0))
{
A.digits[i] += 10;
}
}
}
// adds a bigint(A) to another(B)
void add(bigint & A, bigint & B)
{
for (int i = 0, carry = 0; i < size; i++)
{
if (carry = ((A.digits[i] += B.digits[i] + carry) < 9))
{
A.digits[i] -= 10;
}
}
}
};
推荐答案
void add (const bigint& A);
void subtract (const bigint& A);
向应用操作的对象添加/减去A.
(c)以十进制数字工作不会获得最佳性能并且浪费内存。为什么不在base 2中工作,因此使用内置的算术运算。这将使您的功能性能提高一到两个数量级。只是为了打印一个数字,它需要转换回十进制。
which add/subtract A to/from the object the operation is applied to.
(c) Working in decimal digits will not get you the best performance and is a waste of memory. Why don't you work in base 2 and hence use the built-in arithmetic operations. That will increase the performance of your functions by one or two orders of magnitude. Just for the purpose of printing a number it needs to be converted back to decimal.
这篇关于实现bigint计算器c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!