大数实现(计算器)c ++

时间:2014-11-12 00:25:40

标签: c++ sorting struct

我需要做的是添加此功能:

void decrement_is(bignum & B);

能够从bignum中减去1,完全忽略它的符号, 而不是担心(但观察)如果会发生什么 结果是否定的。

这是我的代码:

#include <iostream>
#include <string>

const bool debugging = false;

const int size = 30;   // I want to make it easy to work with.
// Change to something big later.

struct bignum
{ 
  int digit[size];
  char sign;        // '+' or '-'
  bool ok;
};

// to store the number one thousand six hundred and seventy nine,
// 1679, digit[0]=9, digit[1]=7, digit[2]=6, digit[3]=1, all the rest are zero

void init(bignum & B)
{ 
  for (int i = 0; i < size; i += 1)
    B.digit[i] = 0;
  B.sign = '+';
  B.ok = true; 
}

void print(bignum B)
{
  if (! B.ok)
    cout << "BAD";
  cout << B.sign;
  bool printed = false;
  for (int i = size - 1; i >= 0; i -= 1)
  { 
    int dig = B.digit[i];
    if (debugging)
      cout << "|";
    if (dig != 0 || printed || debugging)
    { 
      cout << dig;
      printed = true; 
    } 
  }
  if (! printed)
    cout << "0"; }

void addsmall_is(bignum & B, int N)  // _is means "ignoring the + or - sign"
  // N must be small.
{
  int toadd = N;
  int position = 0;
  while (toadd > 0)
  { 
    int sum = B.digit[position] + toadd;
    if (sum < 10)
    { 
      B.digit[position] = sum;
      toadd = 0;
    }
    else
    { 
      B.digit[position] = sum % 10;
      toadd = sum / 10; 
    }
    position += 1;
    if (position >= size)
    { 
      B.ok = false;
      break; 
    }
  } 
}

void main()
{
  bignum X;
  init(X);
  while (true)
  { 
    print(X);
    cout << "\n";
    char c;
    int n;
    cin >> c >> n;
    if (cin.fail())
      break;
    if (c == '+')
      addsmall_is(X, n);
    else
      cout << "+ is the only thing I know how to do\n"; 
  }
}

1 个答案:

答案 0 :(得分:0)

void decrement_is(bignum & B) {
    for(int i=0; i<size; ++i) {
        if(--B.digit[i] >= 0) break;
        B.digit[i] = 9;
    }
}

如你所见,这忽略了这个标志。 如果B从0开始,则递减滚动到数字均为9的数字。

这里是一个假定的正整数减法,忽略了bignum的符号。:

void subsmall_is(bignum & B, int N) {
    for(int i=0; i<size && N; ++i) {
        B.digit[i] -= N % 10;
        N /= 10;
        if(B.digit[i] < 0) {
            B.digit[i] += 10;
            ++N;
        }
    }
}

当N> B,结果像以前一样下溢,给出(10 ^大小) - (N-B)

这是完全减法:

void subbig_is(bignum &a, const bignum &b) {
    for(int i=0, borrow=0; i<size; ++i) {
        if(borrow = ((a.digit[i] -= b.digit[i] + borrow) < 0)) {
            a.digit[i] += 10;
}   }   }

增加非常相似,但相反:
o将数字添加到b而不是减去数字 o&#34;借用&#34;是&#34;携带&#34;并且减去而不是添加
o检查&lt; 0变为检查&gt; 9
从溢出的数字中减去o和10,而不是添加