减去一个数组c++中的两个长正整数



我对编程还比较陌生:)。

假设我想创建一个程序,提示用户输入两个50位以内的正数,然后从第一个数字中减去第二个数字。

例如:

用户输入第一个正数:2398340958039458624403859834521849852998358

第二个号码:93954230985312072193422170217372984729812

=================================================

程序输出差异:238894553494092741718901766430812000568564

OR,如果为阴性:-29874430045

=================================================

数字中的每个数字都将作为单独的元素存储在数组中。以下是我目前接受用户输入的方式:

int read_array(int int_array[], int MAX_SIZE) {
    char number;
    int count = 0;
    //set all array entries to 0. 
    for (int i = 0; i < MAX_SIZE; i++){
        int_array[i] = 0;
    }
    do { //processes each individual char in the istream
        cin.get(number);
        // puts char on to the array until it hits the
        // end of the number (end of the line)
        if(( number != 'n') && (count < MAX_SIZE) && (isdigit(number))) {
            int_array[count] = int(number) - int('0');
        }  
        count++; //increments count
    } while (number != 'n');
    //tests if number is too large
    int digitcount = count - 1;
    if (digitcount > MAX_SIZE) {
        cout << endl << "ERROR: The number is above 50 digits!" << endl;
        return 0;
    }

问题:

如何做减法一直困扰着我。我已经试着解决这个问题两周了,很可能是我错过了一些琐碎的事情。

我试过:

  1. 将元素数组转换回一个整数
  2. 写我自己的程序对数字做长减法

等等。。。

但是,只有在达到一定数量的数字和/或它们是正数/负数时,输出才会成功。我很困惑,我不确定最好的方法是减去两个正数数组,得到一个成功的输出,可以容纳正数和负数,如示例所示。非常感谢任何帮助:)。

编辑:我的尝试:

#include "long_sub.h"
#include <sstream>
#include <vector>
using namespace std;
int long_sub(int a[], int b[], const int size) {
    stringstream ss;
    int const sizes = 50;
    int c = 0; //borrow number
    int borrow = 1; // the '1' that gets carried to the borrowed number
    int r[sizes];
    for (int i = 0; i < size; i++) {
        r[i] = 0;
    }    
    //initialise answer array to 0.
    for (int i = size - 1; i >= 0; i--) {
        //handles zeros
        if (a[i] < b[i] && a[i]) {
            //takes the borrow from the next unit and appends to a.
            ss << borrow << a[i];
            ss >> c;
            ss.clear(); // clears stringstream for next potential borrow.
            int temp = c - b[i];
            r[i] = abs(temp);
        } else {
            int temp = a[i] - b[i];
            r[i] = abs(temp);
        }
    }
    for (int i = 0; i <= size - 1; i++ ) {
        cout << r[i];
    }
    cout << endl;
    return r[sizes];
}

因此,此问题的解决方案与手动解决方案基本相同。

如果我们有:

 4321
-1234

你可以取两个数字中的最后一位,从上面的数字中减去下面的数字,1 - 4——这当然意味着你必须从下一位数字中借用,所以我们重新计算,然后得出7。现在,取下一个数字[记住"借"],从2-1=8中减去3。

完全相同的事情是你如何在计算机上对大数字进行减法——一次做一点,如果你"借"了,那么你需要把它带到下一步。

最新更新