gpt4 book ai didi

C 编程——值交换是在随机数组槽中生成新值

转载 作者:行者123 更新时间:2023-11-30 21:25:48 26 4
gpt4 key购买 nike

这是数组:

int deck [52] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11,
2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11,
2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11};
for(i = 0; i < 52; i++){

我用它来交换同一数组中的 2 个值:

    randomNum1 = rand()%53;
randomNum2 = rand()%53;
temp = deck[randomNum1];
deck[randomNum1] = deck[randomNum2];
deck[randomNum2] = temp;
}

我放入打印语句来查看是否可以在数组中找到一个不稳定的特定数字:

for(i = 0; i < 52; i++){
randomNum1 = rand()%53;
randomNum2 = rand()%53;
printf("This is the random number 1: %d\n", randomNum1);
printf("This is the random number 2: %d\n", randomNum2);
temp = deck[randomNum1];
printf("This is the temp and deck[randomNum1] BEFORE: %d and %d\n", temp, deck[randomNum1]);
deck[randomNum1] = deck[randomNum2];
printf("deck[randomnum1]AFTER: %d\n", deck[randomNum1]);
printf("deck[randomNum2]BEFORE: %d\n", deck[randomNum2]);
deck[randomNum2] = temp;
printf("deck[randomNum2]AFTER: %d\n", deck[randomNum2]);
}

它进入的值点总是随机的,并且它变成一个很大的数字。从编译器打印出来:

  1. This is the random number 1: 52
  2. This is the random number 2: 1
  3. This is the temp and deck[randomNum1] BEFORE: 2271744 and 2271744
  4. deck[randumNum1]AFTER: 3
  5. deck[randomNum2]BEFORE:3
  6. deck[randomNum2]AFTER: 2271744

另一个编译器运行:

  1. This is the random number 1: 4
  2. This is the random number 2: 16
  3. This is the temp and deck[randomNum1] BEFORE: 4 and 4
  4. deck[randumNum1]AFTER: 2271744
  5. deck[randomNum2]BEFORE: 2271744
  6. deck[randomNum2]AFTER: 4

在此之前有几个 if 语句和一个 while 循环,但它们都没有触及此数组中的值。有什么建议吗?

最佳答案

您超出了 deck 数组的范围,因为它的有效索引从 0 开始,到 51 结束。您尝试访问索引 52,这会导致未定义的行为。

要避免这种情况,请使用

randomNum1 = rand()%52;
randomNum2 = rand()%52;

关于C 编程——值交换是在随机数组槽中生成新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26702010/

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