gpt4 book ai didi

c++ - 数组内存 C++ 中的可能错误

转载 作者:行者123 更新时间:2023-11-28 06:05:16 28 4
gpt4 key购买 nike

我正在编写一个非常简单的代码来求大数的阶乘。本质上,由于 int 定义导致整体结果溢出,我使用数组来存储单个值。然后我使用加法而不是乘法将数组的各个值添加到它们的特定列中。

该代码基本上减少了 100 x 99,以“将 100 添加到自身 99 次。”

但是,它似乎最初在第一个循环期间有效,但在增加循环次数之后,结果我得到了一个零数组。

对于非结构化代码,我深表歉意,但我一直在修补并试图在旅途中修复它,所以没有太多的逻辑凝聚力。

代码如下:

#include <iostream>

using namespace std;

void printFactorial(int array[], int);

void findFactorial()
{
int initialValue; // Value that will store 100
int num; // 100 - 1 for calculation purposes
int temp; // Stores the initial value temporarily for calculations
long int array1[180]; // This array will hold the total result
long int array2[180]; // This array will change to add to the total result num times

initialValue = 100;

num = initialValue - 1;

temp = initialValue;

for (int i = 0; i <= 170; i++) // Sets the int 100 into the array, with each digit in the corresponding position
{
array2[i] = temp % 10;
temp = temp / 10;
}

while (initialValue != 0) // While loop for recursion
{

for (int i = 1; i <= num; i++) // This causes each digit position to add to itself num times, which is equivalent to
{ // multiplication by num. What I will later do is separate the total sum into its respective
for (int j = 0; j <= 157; j++) // digits position. Say array[2] = 15, I will make array[2] = 5 and add one to array[3].
{
array1[j] += array2[j]; // This causes each digit to add to itself, and store the result in the 'total' array.

}

}

memcpy(array2, array1, sizeof(array1)); // Makes the contents of array2 that of array1, so as to make the next cycle of multiplication
// work.

initialValue--; // Decrease by one since the process must only run 100 times, and then exiting the while loop.
num--;

}

for (int i = 0; i <= 157; i++)
{
cout << array1[i] << " "; // Printing the resultant array.

}

}

int main()
{
findFactorial();
}

最佳答案

您从未初始化 array1,所以它从零开始只是偶然的(您似乎依赖于此)。

您永远不会将任何溢出从 array1 的每个元素传播到下一个元素,这是导致它们通过溢出达到零的主要问题。

由于您似乎打算每个位置只保留一个数字,因此您不需要通过重复加法进行乘法的惊人低效率。一个足够大的 int out 来容纳一个数字乘以你的乘数(只要乘数足够小,整个数组可以容纳阶乘结果)。

考虑类似于以下的内部循环:

temp += num * array[i];
array[i] = temp % 10;
temp /= 10;

那么您就不需要两个数组,每个数组元素只需要保存一个数字。并且 temp 只需要足够大以容纳略大于 9*num(对于最大 num)。

我不想给你更多的细节,因为我假设你这样做是为了练习自己做。否则,您只会使用现有的库。

关于c++ - 数组内存 C++ 中的可能错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32507182/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com