I'm trying to generate 100 distinct random numbers between 0 to 800 and repeat the random number generation 10 times then separate the numbers using a comma but i'm having a problem. In this example i'm using a 2D array to achieve this but I don't seem to get it working.
int main(void)
{
int table[10][10];
int i;
int nSize = sizeof(table)/sizeof(int);
for (i = 0; i < nSize; i++)
{
for (j = 0; j < nSize; j++)
printf("%d,",table[i][j] = rand() % 800);
}
printf("\n");
}
The output is supposed to look something similar to the following:
1, 3, 500, 400, 322, ...
2, 5, 200, 321, 212, ...
500, 433, 421, 354, 545, ...
..
..
..
..
..
..
500, 321, 314, 434, 343, ...
The above is an example and not the actual values.
table
should be 100, since you have 100 random numbers. #define ROW 10
#define COL 10
int array[ROW][COL];
for (i = 0; i < ROW; i++) {
for (j = 0; j < COL; j++) {
array[i][j] = rand() % 801; // if rand() % 800, then it generate 0 - 799, never 800
Just move the printf("\\n")
into the outer for loop and you don't have to use an array:
int main(void)
{
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
printf("%s%d", j > 0 ? "," : "", rand() % 800);
}
printf("\n");
}
}
Note: this will generate numbers between 0 and 799.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.