gpt4 book ai didi

c - 用随机数填充数组并打印到屏幕

转载 作者:太空宇宙 更新时间:2023-11-04 06:28:51 25 4
gpt4 key购买 nike

我是一名初学者,尝试用随机数填充 3x5 二维数组,然后在屏幕上显示高值、低值和平均值。我无法让我的数组打印到屏幕上。有人可以帮忙吗?

#include <stido.h>
#include <math.h>
#include <time.h>

int main (void){
int array [3][5];
int practice_array;
int i, row, col;

srand(time(NULL));

for ( row = 0; row < 3; row +1){

for ( col = 0; col < 5; col +1){

array[row][col] = (rand()%10000) + 1;
}
}
practice_array = array[row][col];
printf("%d", array[row][col]);
return (0);
}

最佳答案

您有 3 个主要问题:

1. 正如 Jongware 在他的评论中所说的 printf应该在循环内部,而不是外部。

2. #include <stido.h>不存在,它是 #include <stdio.h>

3. row +1应该是 row = row + 1 , 或 row += 1 , 或 row++ , 或 ++row (在这种情况下,我们通常使用 row++++row )。当然你需要为 col 做同样的事情


中学:

a. practice_arrayi在这里没用。

b. 您可能忘记了 \nprintf .


我更正了您的代码 + 我添加了最小值、最大值和平均值:

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

#define ROWS_NB 3
#define COLS_NB 5
#define MIN_VAL 1
#define MAX_VAL 10000

int main(void)
{
int array[ROWS_NB][COLS_NB];
int row;
int col;
int val;
int min = MAX_VAL;
int max = MIN_VAL;
int avg = 0;

srand(time(NULL));

for (row = 0; row < ROWS_NB; ++row)
{
for (col = 0; col < COLS_NB; ++col)
{
val = (rand() % (MAX_VAL - MIN_VAL)) + MIN_VAL;
if (val < min)
min = val;
else if (val > max)
max = val;
avg += val;
array[row][col] = val;
//printf("%d ", val);/* uncomment if you want to print the array */
}
//printf("\n");/* uncomment if you want to print the array */
}
avg /= ROWS_NB * COLS_NB;
printf("min: %d\nmax: %d\naverage: %d\n", min, max, avg);
return (0);
}

关于c - 用随机数填充数组并打印到屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22874768/

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