在标准输出中执行打印会导致数组中随机分配值

Executing print in standard output causing random assigning of value in array

本文关键字:数组 随机 分配 标准输出 执行 打印      更新时间:2023-10-16

如果这是一个愚蠢的问题,我很抱歉。我已经为硬币更改问题编写了以下代码。

#include <iostream>
using namespace std;
int coinChange(int coins[], int n, int amount)
{
int combinations[amount + 1];
combinations[0] = 1;
int start;
for(int i = 0; i < n; i++)
{
    start = coins[i];
    int coin = coins[i];
    for(int j = start; j < amount + 1; j++)
    {
        if(j >= coin)
        {
            combinations[j] += combinations[j - coin];
        }
    }
    for(int j = 0; j < amount + 1; j++)
        cout << combinations[j] << " ";
    cout << endl;
}
return combinations[amount];
}
int main(int argc, char const *argv[])
{
int coins[] = {1, 2, 5};
int n = sizeof(coins)/sizeof(coins[0]);
int amount = 12;
// cout << "Total combinations: ";
cout << coinChange(coins, n, amount) << endl;
return 0;
}

代码工作正常,为我提供了正确的输出,如下所示。

1 1 1 1 1 1 1 1 1 1 1 1 1 
1 1 2 2 3 3 4 4 5 5 6 6 7 
1 1 2 2 3 4 5 6 7 8 10 11 13 
13

但是,如果我取消注释main函数中函数调用正上方cout << "Total combinations: ";行,程序会给我奇怪的输出。

Total combinations: 1 32768 32768 32768 44137 44137 44137 44137 196418491 196418492 -790461916 -790429149 619621115 
1 32768 32769 65536 76906 109673 121043 153810 196539534 196572302 -593922382 -593856847 25698733 
1 32768 32769 65536 76906 109674 153811 186579 196605070 196649208 -593812708 -593703036 25885312 
25885312

在函数调用之前执行cout是否会导致此随机输出?或者这对我的编译器版本来说是个问题吗?

初始化(为零(怎么样? combinations

类似的东西

int combinations[amount + 1] {};

否则,combinations[i]的初始值是未定义的不确定的,因此是未定义的程序最终值行为(来自Shafik Yaghmour的更正;谢谢!

coinChange 函数中执行此操作。

int combinations[amount + 1]{};
combinations[0] = 1;
int start;
for(int i = 0; i < n; i++)
{
    start = coins[i];
    int coin = coins[i];
    for(int j = start; j < amount + 1; j++)
    {
        if(j >= coin)
        {
            combinations[j] += combinations[j - coin];
        }
    }
    for(int j = 0; j < amount + 1; j++)
        cout << combinations[j] << " ";
    cout << endl;
}

现在取消注释该行并运行。基本问题是,当您创建combinations数组时,您必须初始化要0的元素。如果你不这样做,他们可能都是幸运的巧合0,但你不能保证这一点。

编辑:使用空的初始值设定项列表启动带有零的数组,如max66建议的那样。