【问题标题】:multiply two arrays like if they were number [closed]将两个数组相乘,就像它们是数字一样[关闭]
【发布时间】:2016-11-26 19:16:01
【问题描述】:

在 C++ 中,最大的 int 值为 2147483647。因此,大于此的整数不能作为整数存储和处理。同样,如果两个正整数之和或乘积大于 2147483647,结果会不正确。

存储和操作大整数的一种方法是将数字的每个单独的数字存储在数组中。

编写一个程序,输入两个最多为 50 位的正整数(它们可以少于 50 位),并且可以对输入的数字进行加法和乘法运算。

如果数字的和或乘数超过 50 位,则输出相应的消息。

您的程序将具有以下功能:
1. 读取数字并将数字存储到数组中的函数
2. 将两个大输入数相乘并输出结果的函数。

您必须执行小学乘法。您不能简单地将数字转换为整数并进行乘法。

请帮忙做乘法。

有没有什么方法可以在不使用一些更高级的函数的情况下使用 C++ 中的数组来做到这一点。

【问题讨论】:

  • 我们希望您能带着一个具体的问题来这里尝试。不是“我怎么做作业?”
  • 你必须像在纸上计算一样实现它,这一点都不难。只需检查您是否随身携带。
  • 请编辑您的问题,澄清“...不使用一些更高级的功能”。 C++ 没有矩阵乘法。

标签: c++ arrays logic multiplication


【解决方案1】:

既然你知道最大位数是 50,你可以使用数组:

const unsigned int MAXIMUM_DIGITS = 50U;
char number_digits[MAXIMUM_DIGITS];

通过保留为字符,您无需执行任何除法即可从数字中提取数字。

要将字符转换为内部数字,可以使用:

unsigned int number = number_digit[i] - '0';

或者搜索一个数组:

char decimal_digits[] = "0123456789";
char * p = strchr(decimal_digits, number_digit[i]);
unsigned int number = p - &decimal_digits[0];

数字的乘法留作 OP 的练习。

编辑 1:乘法
一个乘法算法是:

unsigned int carry = 0U;

// Multiply the two digits
// The two digits should be unsigned int
unsigned int product = digit_1 * digit_2;

// Add in the carry from a previous multiply
product += carry;

// Calculate carry (overflow) from the product.
carry = product / 10;

// Trim the product to one digit.
product = product % 10;

【讨论】:

    猜你喜欢
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多