C语言如何统计二维数组中不同元素的出现次数
C语言统计二维数组中不同元素出现次数的实现方法
你现有代码中的判断条件array[j][i] == array[j][i]是恒成立的逻辑,只能统计出数组的总元素个数,无法实现按不同元素分类计数的需求。
修正后可直接运行的完整代码
#include <stdio.h> int main(){ // 定义各数字对应的计数器 int one = 0; int two = 0; int three = 0; int five = 0; int six = 0; char array[3][5] = { {'1', '3', '3', '5', '1'}, {'2', '1', '5', '6', '2'}, {'6', '2', '5', '5', '2'} }; // 遍历二维数组所有元素 for(int j = 0; j < 3; j++){ for(int i = 0; i < 5; i++){ // 匹配到对应数字就给对应计数器+1 switch(array[j][i]) { case '1': one++; break; case '2': two++; break; case '3': three++; break; case '5': five++; break; case '6': six++; break; default: break; } } } // 按要求格式输出结果 printf("number one is found %d times in array\n", one); printf("number two is found %d times in array\n", two); printf("number three is found %d times in array\n", three); printf("number five is found %d times in array\n", five); printf("number six is found %d times in array\n", six); return 0; }
代码说明
- 遍历二维数组的每个元素,用switch分支匹配字符类型的数字,匹配成功就给对应计数器累加,逻辑简单直观
- 如果后续数组内的数字范围扩大,可改用计数数组实现:将字符数字转为整型后作为数组下标,直接累加计数,无需写多个分支,扩展性更好
运行输出结果
number one is found 3 times in array
number two is found 4 times in array
number three is found 2 times in array
number five is found 4 times in array
number six is found 2 times in array
内容的提问来源于stack exchange,提问作者david
相关产品推荐
相关产品推荐

