c - 如何根据打印的数组增加计数器

标签 c arrays if-statement random counter

我成功地使用随机数和数组开发了一个简单的 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

我尝试将 if 语句中的 randomNumber 替换为 board[rows][columns],但我似乎得到了相同的不期望的结果。

最佳答案

数组索引错误。

改变

for (rows = 1; rows <= 5; rows++)   

for (rows = 0; rows < 5; rows++)    

cols类似。 C 中的数组是从 0 索引的。

关于c - 如何根据打印的数组增加计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19499032/

相关文章:

c - 如何将文件内容重定向到标准输入,为什么 exec 函数不起作用?

java - codingbat 递归练习

java - for循环中的if else语句?

php - 如何对多维数组进行urlencode?

c++ - 隐式使用类对象作为条件 C++

javascript - 这个 JavaScript if/else 语句有什么问题?

c - 从命令行使用 Visual Studio 2013 编译 aritchk.c 时出现未解析的符号

将十进制转换为十六进制,然后进行十六进制数学运算

c++ - ld : foo. o :foo. h :6 multiple definition of `bar' foo. h:6: 首先在这里定义

java - java中二维矩阵乘法的问题