gpt4 book ai didi

c - 使用数组和随机数循环打印一个简单的 5 x 5 板

转载 作者:行者123 更新时间:2023-11-30 17:45:55 26 4
gpt4 key购买 nike

我之前在Generating Unique Random Numbers in an Array using Loop问过一个非常复杂的问题

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

所以现在我正在尝试使用带有随机数的数组创建一个 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];是我认为我真的很困惑的地方。我真的不知道该怎么办。

我正在尝试将随机数分配到棋盘中,但我犯了严重错误。

各位有什么指点吗?

最佳答案

尝试这样的事情:

#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

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

关于c - 使用数组和随机数循环打印一个简单的 5 x 5 板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19492456/

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