C100囚犯谜语,我的代码有问题

eqqqjvef  于 2023-10-15  发布在  其他
关注(0)|答案(3)|浏览(79)

(If你已经知道这个谜语是关于什么的了,只要读最后两行)
我看过一个谜语的视频,叫做“百名囚犯之谜”,它基本上告诉你,(一次只能一个人)进入一个房间,这个房间里有盒子,盒子的顺序是从1到100,但是盒子里的数字是随机的,每个进入房间的囚犯也是从1到100,所以每个囚犯必须选择有他的号码的盒子,每个囚犯有一组尝试(50次尝试),如果他打开50个盒子,他没有找到他的号码,他输了!例如,囚犯1号进入房间,他必须找到有他的号码的盒子。可能是7号或19号或27号盒子谁知道呢!所以这只是一场运气的游戏。或者是吗?游戏有策略和方法来数学解决难题,但这不是我的问题,我只是想在C中编程游戏,为自己解决难题,代码中有很多漏洞,所以仔细看看它,找到问题所在,谢谢大家:)!

#include <stdio.h>
#include <stdlib.h>

int main() {
    int i, j = 0, k = 0, counter = 0;
    int boxes[10];
    int boxEntered;
    for (i = 0; i <= 10; i++) \\ numbering the array
        boxes[i] = i;
    for (i = 0; i <= 10; i++) {    
        int temp = boxes[i];
        int randomIndex = (rand() % 10); \\ shuffling the boxes to put random numbers
        boxes[i] = boxes[randomIndex];
        boxes[randomIndex] = temp;
    }
    for (i = 0; i <= 10; i++) {
        printf("%d : (%d)\n", boxes[i], i); \\ print the boxes randomized and their index ordered
    }
    printf("You only have 5 tries!\n");
    while (k != 5) {
        while (j < 10) {
            printf("Pick a box number between 0 and 10 (You are number %d)\n",counter);
            scanf("%d",&boxEntered);
            if (boxes[boxEntered] == boxes[counter]) {
                printf("\nYou succeded, PROCEED TO NEXT PRISONER\n");
                j++; \\ go to the next iteration
                k = 0; \\ set tries back to 0
                counter++; 
            } else
                printf("Try again\nThe box you entered had number %d\n",boxes[boxEntered]);
            k++;
            if (k == 5) { \\ if player prisoner fails 5 times you break the loop
                break;
            }
        }
    }
    if (counter == 10) { \\ if last prisoner was reached successfully then game is won
        printf("You are freed!");
    } else {
        printf("You are going back heheheheheh!\n")
    }
    return 0;
 }

正如你可以看到在这张图片的输出没有任何意义,在所有,我不知道什么是错在这里。

pgccezyw

pgccezyw1#

从代码的逻辑来看,您应该将

boxes[boxEntered] == boxes[counter]

boxes[boxEntered] == counter

这是因为counter在这里似乎代表一个囚犯。取boxes[counter]会给你一个给予盒子,这不是你想要的;你是想看看这个盒子是否和现在的犯人匹配
另一个重要的注意事项是,以下代码将超出数组的范围,导致未定义的行为:

for (i = 0; i <= 10; i++) boxes[i] = i;

boxes被声明为大小为10,因此取boxes[10]超出了界限;最大值为boxes[9]
要解决这个问题,可以从1开始索引数组。要在C中执行此操作,请使用boxes[11],而不是声明boxes[10]。这将确保您可以访问boxes[10]
然后你可以改变你的循环从1开始,所以类似于:

for (i = 1; i <= 10; i++) boxes[i] = i;

请确保对代码中的每个数组和for循环进行此更改。

uemypmqf

uemypmqf2#

给你我已经做了一些编辑到您的程序(它实际上是一个伟大的计划!- 我喜欢!我只做了一些小的修改,但它确实有效(首先,我添加了srand()函数,这样你的程序每次都会产生不同的结果。此外,主要的罪魁祸首是这一行:if(boxes[boxEntered] == boxes[counter])应该是if(boxes[boxEntered] == counter)。

#include <stdio.h>
#include <stdlib.h>
#include <time.h.>

int main()
  {
  int i, j = 0, k = 0, counter = 0;
  int boxes[10];
  int boxEntered;
  int temp;
  int randomIndex;
  time_t now;//Declaring time-type variable.

  time(&now);//Storing system time into now.
  srand(now);//Seeding the random number generator with system time.

  for (i = 0; i < 10; i++) // numbering the array
    { boxes[i] = i; }

  for (i = 0; i < 10; i++)
    {
    temp = boxes[i];
    randomIndex = (rand() % 10); // shuffling the boxes to put random numbers
    boxes[i] = boxes[randomIndex];
    boxes[randomIndex] = temp;
    }

  for (i = 0; i < 10; i++)
    {
    printf("Box# %d =  %d\n", i, boxes[i]); // print the boxes randomized and their 
                                            //index ordered
    }

  printf("You only have 5 tries!\n");
  while (k != 5)
    {
    while (j < 10)
      {
      printf("Pick a box number between 0 and 10 (You are number %d)\n",counter);
      scanf("%d",&boxEntered);
      if (boxes[boxEntered] == counter)
        {
        printf("\nYou succeded, PROCEED TO NEXT PRISONER\n");
        j++; // go to the next iteration
        k = 0; // set tries back to 0
        counter++;
        }
        else
          {
       printf("Try again\nThe box you entered had number  %d\n",boxes[boxEntered]);
          k++;
          if (k == 5) // if player prisoner fails 5 times you break the loop
          { break; }
          }
      }

  if (counter == 10)  // if last prisoner was reached successfully then game is won
       {
       printf("You are freed!");
       break;
       }
    else
      { printf("You are going back heheheheheh!\n"); }
     }
  return 0;
  }
ymdaylpp

ymdaylpp3#

老实说,我没有读过你的代码。只是使用单字符变量名是我的一个小毛病(无意冒犯)。总之,我目前正在写一本关于C编程语言的初学者书籍。下面的程序(用C写的)可以模拟100个囚犯问题。该程序执行1000次试验,然后最终产生结果的输出(成功率的百分比)。

// This program simulates the 100 prisoner problem.
#include <stdio.h>
#include <stdlib.h>
#include <time.h.>

    int boxNumber[100] = {0};//Declaring global integer array (100 "boxes" from 0 to 
                             //99).
    
    float flag=0.0; //Declaring global variable for keeping track of success rate.
    
    void seedRandom(); //Seeds the srand() function with current time.
    void writeNegative();//Fills entire global integer array with -1.
    void writeValue();//Writes values into each "box" (integer array).
    void prisoners(); //Prisoners check each box.
    void loop(); //Runs program for 1000 trials (should yield about 31 percent success rate).
    
    int main()
    {
    int cntr;
    
    seedRandom();
    loop();
    
    printf("\n\nThere was a %.0f percent success rate.\n\n", flag/1000*100);
    
    return 0;
    }
    //-------------------------------------------------------------------------------------
    void loop()
    {
    int cntr;
    for (cntr=0;cntr<1000;cntr++)
      {
      writeNegative();
      writeValue();
      prisoners();
      }
    }
    //-------------------------------------------------------------------------------------
    void seedRandom()
    {
    time_t now;//Declaring time-type variable.
    time(&now);//Storing system time into now.
    srand(now);//Seeding the random number generator with system time.
    }
    //-------------------------------------------------------------------------------------
    void writeNegative()
    {
    int cntr;
    for (cntr=0;cntr<100;cntr++)//Writing -1 into each array subscript.
       { boxNumber[cntr]=-1; }
    }
    //-------------------------------------------------------------------------------------
    void writeValue()
    {
    int cntr=0; //Used for writing a value into each of the 100 "boxes"
                //starting with 0.
    int select; //Used to randomly select a box.
    while (cntr<100)//Writes a value into each box.
      {
      select=rand()%100;//Writing random number into select (must be less than 100).
      if (boxNumber[select]==-1) //Selects a box randomly. We only want to
        {             //write into a box that hasn't been filled yet.
        boxNumber[select]=cntr;  //Writing value into box.
        cntr++;  //Incrementing to next value.
        }
      }
    }
    //-------------------------------------------------------------------------------------
    void prisoners()
    {
    int cntr; //Counts 50 chances for prisoner to check boxes.
    int psnr; //Indicates prisoner number.
    int currentBox; //
    int success=0;
    for (psnr=0;psnr<100;psnr++)
       {
       currentBox=psnr;//Prisoner starts with his box number.
       for (cntr=0;cntr<50;cntr++)//Prisoner gets 50 chances.
         {
         if(boxNumber[currentBox]==psnr)//Prisoner starts with his box number.
           {
           printf("Success! Prisoner %d = box %d\n",psnr,currentBox);
           success++;
           break;//Breaks current loop & moves onto next prisoner.
           }
           else
             { currentBox=boxNumber[currentBox]; }//Prisoner goes to box number that
         }                      //was written inside previous box.
       }
    if (success==100)
       { printf("Congratulations! All the prisoners have made it.\n\n");
    flag=flag+1.0; //Counts number of successes.
      }
    
       else
         { printf("Only %d were successful.\n\n",success); }
    }

相关问题