部分乘法的输出错误

问题描述 投票:0回答:1

我尝试使用传统方法来实现乘法,将进位和部分分开并将它们加在一起。但我的代码没有给我正确的输出。我被这段代码困住了,想知道我的概念和对这个概念的理解是否错误。
这里我提供我的代码

#include<iostream>
#include<string>

using namespace std;

int main() 
{ 
    int A[] = {5, 2, 3, 0, 1}; 
    int B[] = {3, 0, 8}; 
    int size_A = sizeof(A) / sizeof(A[0]); int size_B = sizeof(B) / sizeof(B[0]); 
    int size_result = size_A + size_B + 1; 
    int* result = new int[size_result]; // Allocate memory for the array fill(result, result + size_result, 0); // Initialize result array with 0s

    for (int i = size_A - 1; i >= 0; i--)
    { 
        for (int j = size_B - 1; j >= 0; j--) 
        { 
            int partial = A[i] * B[j]; 
            int position1 = i + j + 1; 
            int position2 = i + j;

            result[position1] += partial % 10; result[position2] += partial / 10;

            if (result[position1] >= 10) { result[position1 - 1] += result[position1] / 10; result[position1] %= 10; }

            if (result[position2] >= 10) { result[position2 - 1] += result[position2] / 10; result[position2] %= 10; }
        }
    }

// Normalize the result to remove leading zeros 
    int startPos = 0; 
    while (result[startPos] == 0 && startPos < size_result - 1) { startPos++; }

// Print the result 
    for (int i = startPos; i < size_result; i++) 
        { cout << result[i]; }
            
    delete[] result;// Free allocated memory
} // return 0; 

我希望有人可以帮助我修复此代码并帮助我更多地了解此乘法算法的概念。
如果你用Java来回答这个问题就可以了

c++ arrays algorithm multiplication
1个回答
0
投票

我希望有人可以帮助我修复此代码并帮助我更多地了解此乘法算法的概念。

您应该能够使用这个示例来修改您自己的方法。 首先,我定义了一些辅助方法,用于将字符串转换为数组。这样您就可以直观地将结果与实际的

BigInteger
乘法进行比较。

Function<String, int[]> toArray = n -> Arrays.stream(n.split(""))
        .mapToInt(Integer::parseInt)
        .toArray();

现在根据一些数字创建数组并显示它们

String aa = "52301";
String bb = "308";
int[] a = toArray.apply(aa);
int[] b = toArray.apply(bb);
System.out.println(Arrays.toString(a));
System.out.println(Arrays.toString(b));
System.out.println();

算法

  • 分配一个等于两个源数组长度的结果数组。
  • nextPos
    是开始产品的地方。就像在每个后续乘法行上向左移动一样。第一次执行此操作从结果数组的末尾开始。
  • 现在使用两个嵌套循环以相反的顺序独立迭代数组。
    • 首先将两个数组元素相加
    • 然后将进位移动到左侧相邻的单元格。
    • 然后将之前的和替换为余数/10(使用%)
    • 更新
      s
      到下一个位置。
  • 内循环完成后,将
    nextPos
    向左调整
    1
int[] result = new int[a.length + b.length + 1];
int nextPos = 1; //start position from array length

for (int i = a.length - 1; i >= 0; i--) {
    int s = result.length - d;
    for (int k = b.length - 1; k >= 0; k--) {
        result[s] += (a[i] * b[k]);  
        result[s - 1] += result[s] / 10;
        result[s] = result[s] % 10;
        s--;
    }
    nextPos++;

}

显示与

BigInteger
产品相比的结果

System.out.println(Arrays.toString(result));
String sum = new BigInteger(aa).multiply(new BigInteger(bb)).toString();
System.out.println(Arrays.toString(sum.split("")));

打印

[5, 2, 3, 0, 1]
[3, 0, 8]

[1, 6, 1, 0, 8, 7, 0, 8]
[1, 6, 1, 0, 8, 7, 0, 8]
© www.soinside.com 2019 - 2024. All rights reserved.