在标准输出中执行打印会导致数组中随机分配值
Executing print in standard output causing random assigning of value in array
如果这是一个愚蠢的问题,我很抱歉。我已经为硬币更改问题编写了以下代码。
#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建议的那样。
相关文章:
- 在将数字随机生成为数组期间从内存输出随机数的数组
- 将随机生成的数字添加到数组 + 对这些数组求平均值
- C++具有随机计数的数组
- 从C++数组中选择一个随机元素
- 为什么我的 2d 数组的第二行从 RAM 中获取随机值?
- 该程序将.csv文件中的一系列单词放入数组中,然后随机生成句子.但它不起作用
- 为什么我的数组值会更新为随机值?
- 在 c++ 的 10x10 数组中生成特定数量的多个随机字符
- SFINAE - 检测类型 T 是指针、数组还是带有随机访问运算符的容器,以及给定的值类型
- 动态数组传递给 main 中用随机值填充的函数,返回值3221226356
- 选择随机字符串数组的排序
- 如何在 3x4 数组中随机 4 个不同的位置
- 字符数组中的十六进制导致写入套接字时出现随机字符
- 更快地访问 C++ 数组中的随机元素
- 通过数组C 随机增加
- C++ 数组随机播放不起作用
- 将多维数组随机化(随机播放)为另一个 2D 数组
- 使用二维数组随机生成器objective c和c++
- 数组随机存取c++
- 多维数组随机漫步程序