【问题标题】:Taking a Big Integer Input [closed]采用大整数输入[关闭]
【发布时间】:2015-08-12 13:09:17
【问题描述】:

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

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

【问题讨论】:

标签: c++ arrays integer


【解决方案1】:

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

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

例如,要计算两个数字的前两位之和,您可以这样做

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

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

【讨论】:

  • 但是我们不能简单地对字符串进行操作,对吧?我们需要先将字符串中的字符转换为整数不是吗?
  • @powersource97 正确。
  • @6502 你能详细说明一下你打算如何将该字符1 转换为整数1 吗?
  • @powersource97 查看 ASCII 表,您只需执行 '1' - '0'。 (为什么?使用 asciitable.com 找出答案。)
【解决方案2】:

相反,这次用户将输入一个非常大的数字,其中包含 1000 位数字,我必须以某种方式将其存储在一个整数数组中,每个数组元素中的数字的每个数字都如上所述.

答案:分配动态内存。

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... */

【讨论】:

  • Eww。那不是答案。答案是使用std::stringstd::vector 并避免进行手动内存操作
  • @NathanOliver 他想要一个数组,而不是std::vector。阅读规格。
  • @Don 这里有一个缺陷。数量很大,一开始就无法存入int theNumber
  • 我们应该引导他采取更好的方法。如果他们问他们是否使用什么刀片来切断他们的手来止痒,我们不应该推荐刀片,而是将他们指向止痒粉。
  • 已修复。 @NathanOliver 我将为这种替代方法编辑我的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
  • 2012-09-19
  • 2012-11-04
  • 1970-01-01
  • 2011-04-27
  • 1970-01-01
相关资源
最近更新 更多