接受一个大整数输入

Taking a Big Integer Input

我想创建一个程序来处理大于 C++ int 可以存储的整数。

我想首先将用户输入的整数存储在一个integer数组中,这样输入数字的每个数字都存储在每个数组槽中,比如968,它最终应该存储在数组使得 arr[0] is 9, arr[1] is 6, arr[2] is 8。相反,这次用户将输入一个 very huge number ,其中包含 1000 个数字,我必须以某种方式将其存储在一个整数数组中,每个数组元素中的数字的每个数字如上所述。 那么有人可以解释一下 big int 库的用法吗?

您可以只使用 std::string 对象。

每个字符都在 '0''9' 之间,您可以使用它来进行计算。

例如,计算两个数的前两位数字之和

int sum = (a[0] - '0') + (b[0] - '0');

提示:如果您保留 num[0] 最低有效位(即通常写入最右边的位置),则编写计算算法会更容易一些。

Instead, this time user will be inputting a very huge number with say, 1000 digits in it and I have to somehow get it to be stored in an integer array, with each digit of the number in each array element as cited above.

回答:分配动态内存。

int variableSize;
char* theNumber;
std::cout << "What is your preferred size? ";
std::cin >> variableSize; /* do some error checking if necessary*/
int* myNumber = new int[variableSize];
std::cout << "Input the number now: ";
std::cin >> theNumber;
/* use a for loop to put each char into its respective array location;
do not forget to convert char to int... */

更喜欢使用 std::vector(存储动态内存的首选方式)?这是该方法:

int variableSize;
char* theNumber;
std::cout << "What is your preferred size? ";
std::cin >> variableSize; /* do some error checking if necessary*/
std::vector<int> myNumber(variableSize);
std::cout << "Input the number now: ";
std::cin >> theNumber;
/* use a for loop to put each char into its respective array location;
do not forget to convert char to int... */