我设法使用随机数和数组开发了一个简单的5x5电路板。像我这样的人的巨大成就! :)
现在我必须根据数字的频率递增计数器。
如果打印了0-49之间的值,那么nCounter ++ 如果打印出50-75之间的值,那么pCounter ++就是这样的。
问题是我不知道如何根据印刷电路板增加计数器。
以下是代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
//Initialize Variables
int randomNumber;
int rows;
int columns;
int hdCounter =0;
int hCounter = 0;
int cCounter = 0;
int pCounter = 0;
int nCounter = 0;
//Declare board size
int board[5][5]; //size of board is 5 x 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 = 1; rows <= 5 ; rows++ )
{
//Create the colimns for the board
for ( columns = 1; columns <= 5 ; columns++ )
{
//Assign variable randomNumber into variable board
randomNumber = rand() %100 + 1;
board[rows][columns] = randomNumber;
//print the board
printf("%d\t", board[rows][columns]);
//calculate the frequency of numbers on the printed board
if (randomNumber >= 85 && randomNumber <= 100 )
hdCounter++;
else if ( randomNumber >= 75 )
hCounter++;
else if ( randomNumber >= 65 )
cCounter++;
else if ( randomNumber >= 50 )
pCounter++;
else if ( randomNumber >= 1 )
nCounter++;
else
continue;
}
//Newline after the end of 5th column.
printf("\n\n");
}
printf( "N \t P \t C \t H \t HD\n\n" );
printf("%d \t %d \t %d \t %d \t %d \t",
nCounter, pCounter, cCounter, hCounter, hdCounter);
}//end main
我尝试用randomNumber
替换if语句中的board[rows][columns]
,但我似乎得到了相同的不良结果。
答案 0 :(得分:0)
错误地索引数组。
更改
for (rows = 1; rows <= 5; rows++)
到
for (rows = 0; rows < 5; rows++)
同样适用于cols
。数组在C中为0索引。