【发布时间】:2013-11-08 08:55:20
【问题描述】:
好的,所以我创建了一个程序,该程序成功创建了一个二维数组并将随机数存储在数组中,并确定使用数组和 for 循环语句创建的随机数的最高、最低和平均值。但是我有一种感觉,我的代码有问题,但无法弄清楚。我相信这与我使用的 for 循环语句有关。
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROW 3
#define COLUMN 5
int main( void )
{
int randnum_array [ROW] [COLUMN];
int highrn = 0 , lowrn = 9999999 , total = 0 , nextvalue = 0;
int r = 0 , c = 0 , lr = 0 , lc = 0 , hr = 0 , hc = 0;
float average = 0.0;
srandom ( (unsigned) time (NULL) );
printf( "\n Welcome User, this program creates an array random numbers "
"and stores them into each \n of the 11 elements of the rand_num "
"array. The program then displays the \n highest, lowest, "
"and average of the numbers created.\n\n" ) ;
printf(" Contents of randnum_array:\n\n");
for (r = 0; r < ROW ; r++)
{
for (c = 0; c < COLUMN ; c++)
{
nextvalue = random ( ) % 10001;
printf(" Value in randnum_array row %d column %d is: %d\n", r+1 , c+1 , nextvalue);
randnum_array [r] [c] = nextvalue;
if (nextvalue > highrn)
{
highrn = nextvalue;
hr = r;
hc = c;
}
if (nextvalue < lowrn)
{
lowrn = nextvalue;
lr = r;
lc = c;
}
total = total + nextvalue;
}
}
average = (float)total / (ROW * COLUMN);
printf("\n The lowest value is %d in row %d column %d.", lowrn , lr+1 ,
lc+1 ) ;
printf("\n The highest value is %d in row %d column %d.", highrn , hr+1 ,
hc+1) ;
printf("\n The average of all of the numbers in the randnum_array"
" is: %-7.3f", average ) ;
printf("\n\n Thank you for using this program\n\n" ) ;
return ( 0 ) ;
}
这是输出:
Welcome User.
Contents of randnum_array:
Value in randnum_array row 1 column 1 is: 2375
Value in randnum_array row 1 column 2 is: 102
Value in randnum_array row 1 column 3 is: 1754
Value in randnum_array row 1 column 4 is: 6464
Value in randnum_array row 1 column 5 is: 3237
Value in randnum_array row 2 column 1 is: 3495
Value in randnum_array row 2 column 2 is: 2221
Value in randnum_array row 2 column 3 is: 5663
Value in randnum_array row 2 column 4 is: 885
Value in randnum_array row 2 column 5 is: 8442
Value in randnum_array row 3 column 1 is: 4465
Value in randnum_array row 3 column 2 is: 4561
Value in randnum_array row 3 column 3 is: 9182
Value in randnum_array row 3 column 4 is: 1781
Value in randnum_array row 3 column 5 is: 7478
The lowest value is 102 in row 1 column 2.
The highest value is 9182 in row 3 column 3.
The average of all of the numbers in the randnum_array is: 4140.333
Thank you for using this program
谁能给我一些关于代码可能有问题的建议,或者它是否可以。一切正常,但由于我之前从未使用过 2D 数组,所以我不太确定自己在做什么。
【问题讨论】:
-
lowrn = 9999999超出了int的范围。 -
所以我应该把它改成不同的数字吗?我听说您应该将低变量初始化得非常高。
-
你可以使用limits.h中的
INT_MAX和INT_MIN。 -
我的教授还没有教我们如何使用这些,而且我们不允许使用他还没有教过的任何东西,这有点令人讨厌。我可以将其设置为 9999 吗?
标签: c for-loop multidimensional-array