arrays - 如何计算 C 语言中二维数组中特定字符的出现次数?
问题描述
我有一个数组 [8][8]
char d[ROWS][COLS] = {
{0, 2, 0, 2, 0, 2, 0, 2},
{2, 0, 2, 0, 2, 0, 2, 0},
{0, 2, 0, 2, 0, 2, 0, 2},
{1, 0, 1, 0, 1, 0, 1, 0},
{0, 1, 0, 1, 0, 1, 0, 1},
{3, 0, 3, 0, 3, 0, 3, 0},
{0, 3, 0, 3, 0, 3, 0, 3},
{3, 0, 3, 0, 3, 0, 3, 0}};
int countOccurrences(char d[ROWS][COLS], int i, int j, int res)
{
res = 0;
for (i=0; i<=ROWS; i++){
for(j=0; j<=COLS; j++){
if ('2' == d[ROWS][COLS])
res++;
}
}
return res;
printf("score%d", res);
}
我的代码不起作用,我需要在 2D 数组中查找并计算出现次数并将其打印出来
解决方案
我发表了评论,但我也会继续使用固定功能做出回应。我将指出代码中的三个主要问题:
- 在您的代码中,您在数组中有数字,但随后您尝试将 char 与数字进行比较(
'2' == 2
为 false),这意味着您的结果将全部为 0 - print 语句在之后,
return
这意味着它实际上不会运行。 - if 语句
if (2 == d[ROWS][COLS])
总是要检查位置ROWS
和处的数字COLS
。第一个问题是ROWS
并且COLS
没有改变位置,这是一个常数;你想检查位置i
和j
。其次,由于 C 中的数组是从零开始的,因此d
在位置访问[ROWS][COLS]
实际上将指向一些未知的内存空间,因为这超出了数组的范围,但这只是一个有趣的事实。
以下代码应该可以解决我上面指出的问题:
char d[ROWS][COLS] = {
{0, 2, 0, 2, 0, 2, 0, 2},
{2, 0, 2, 0, 2, 0, 2, 0},
{0, 2, 0, 2, 0, 2, 0, 2},
{1, 0, 1, 0, 1, 0, 1, 0},
{0, 1, 0, 1, 0, 1, 0, 1},
{3, 0, 3, 0, 3, 0, 3, 0},
{0, 3, 0, 3, 0, 3, 0, 3},
{3, 0, 3, 0, 3, 0, 3, 0}};
int countOccurrences(char d[ROWS][COLS], int i, int j, int res) {
res = 0;
// NOTICE that it is now i < ROWS and j < COLS instead of
// i <= ROWS and j <= COLS to deal with what I mentioned
// before about the zero-based indexing in C, which means
// we need to stop BEFORE ROWS and COLS
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
if (2 == d[i][j])
res++;
}
}
printf("score%d", res);
return res;
}
推荐阅读
- html - 父 div 在其元素之前变小
- amazon-web-services - EC2:在我自己创建的 VPC 中启动公共 EC2 时出现此错误
- c# - 不改变 JSON 的 JSON 数组的 NewtonSoft 继承反序列化
- python - 获取不在不同模型的多对多关系中的对象?
- c - 在驱动程序的上下文中,术语“框”是什么意思?
- java - 如何在停止异步方法期间避免 java.nio.channels.ClosedByInterruptException 异常
- django - 如何获得模型字段的指定?
- apache-kafka - 设计 Kafka 消费者和生产者以实现可扩展性
- fortran - 以可移植方式获取 Fortran 中所有环境变量的列表?
- html - 如何删除嵌入的 YouTube 视频下方的区域?