0

在使用循环生成数组中的唯一随机数之前,我问了一个非常复杂的问题

但是我发现我还不能理解所有的概念,还有太多未知的东西,所以我决定一步一步地学习它。

所以现在我正在尝试使用带有随机数的数组创建一个 5x5 板。这是我的代码:

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

    //Declare the board size and other variables//

    //Create the random number generator seed

    //Loop to create the wanted board size

    //Plant the random numbers into the board within the loop

    int main()

    {
    //Initialize Variables
    int randomNumber;
    int rows;
    int columns;

    //Declare board size. Size of board is 5 x 5
    int board[5][5]; 

    //Create the random number generator seed
    srand(time(NULL));

    //Assign the random numbers from 1 - 25 into variable randomNumber
    randomNumber = rand() %25 + 1;

    //Create the rows for the board
        for ( rows = 1; rows <= 5 ; rows++ )
        {
            //Create the columns for the board
            for ( columns = 1; columns <= 5 ;  columns++ )
             {
             //Assign variable randomNumber into variable board
             board[randomNumber][randomNumber];
        }
            //Newline after the end of 5th column.
            printf("\n");
    }

    //Print the board
    printf("%d\t", board[randomNumber][randomNumber]);

}//end main

最后一部分board[randomNumber][randomNumber];是我认为我真的很困惑的地方。我真的不知道该怎么办。

我正在尝试将随机数分配到板上,但我弄错了。

各位大侠有什么指点吗?

4

1 回答 1

0

尝试这样的事情:

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

//Declare the board size and other variables//

//Create the random number generator seed

//Loop to create the wanted board size

//Plant the random numbers into the board within the loop

int main()

{
//Initialize Variables
int randomNumber;
int rows;
int columns;

//Declare board size. size of board is 5 x 5
int board[5][5]; 

//Create the random number generator seed
srand(time(NULL));

//Assign the random numbers from 1 - 25 into variable randomNumber

//Create the rows for the board
    for ( rows = 0; rows < 5 ; row++ )
    {
        //Create the columns for the board
        for ( columns = 0; columns < 5 ;  columns++ )
         {
         //Assign variable randomNumber into variable board
         randomNumber = rand() %25 + 1;

         board[rows][columns] = randomNumber;
         printf("%d\t", board[rows][columns]);

    }
        //Newline after the end of 5th column.
        printf("\n");
}

}//end main

您需要使用=Operator 将生成的编号分配给 Board。您所做的只是在 1-25 范围内打印一个随机行和列 - 所以大多数时候您可能会在这里得到一个异常,如果它有效,则您的数组未填充,因此默认情况下具有值(作为您的数组在方法内部定义,那里有一些随机值,但你不能确定那里有什么,直到你用值填充它)

于 2013-10-21T10:52:00.687 回答