减去一个数组c++中的两个长正整数
Subtracting two long positive integers in an array 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;
}
问题:
如何做减法一直困扰着我。我已经试着解决这个问题两周了,很可能是我错过了一些琐碎的事情。
我试过:
- 将元素数组转换回一个整数
- 写我自己的程序对数字做长减法
等等。。。
但是,只有在达到一定数量的数字和/或它们是正数/负数时,输出才会成功。我很困惑,我不确定最好的方法是减去两个正数数组,得到一个成功的输出,可以容纳正数和负数,如示例所示。非常感谢任何帮助:)。
编辑:我的尝试:
#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。
完全相同的事情是你如何在计算机上对大数字进行减法——一次做一点,如果你"借"了,那么你需要把它带到下一步。
- C++需要帮助从用户那里获得一个整数,并确保它在另外两个整数之间
- 比较C++中两个整数的最有效和最干净的方法是什么?
- 比较两个整数在C++中与未知 int 类型的相等性
- 如何组合两个整数向量
- 在两个整数之间交换最右边的N位
- 打印出两个整数之间的偶数
- Python 等效代码,可像C++一样直接附加两个整数
- 移位运算符如何在查找两个整数中的不同位数?
- 运算符"|"如何计算两个整数?
- 如何找出在两个整数的乘积中设置了多少位(等于 1)
- 当键是两个整数时,C 地图或unordered_map
- C 将两个整数进入队列
- 比较 C++ 字符串打印中的两个整数数组
- 为什么双精度不存储两个整数的乘积
- C++将字符串输入拆分为两个整数
- C 中的内存模型:为什么在同一内存位置分配了结构中的两个整数
- 获取所有方式以两个整数的产品表示数字
- Systemc传输级建模从TLM_Generic_Payload提取两个整数
- 数据的所有组合都是产品的两个整数
- 编写一个功能,该函数将使用框架交换两个整数