计算字符串中数字出现的次数 [英] Count number of occurrences of a digit within a string
本文介绍了计算字符串中数字出现的次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
因此,我试图计算数组中每个数字的出现次数.
So I'm trying to count the number of occurrences of each digit within an array.
到目前为止,我的代码如下:
My code I've got so far looks like the following:
#include <stdio.h>
#include <string.h>
int main()
{
int numbers [10]= {1, 4, 5, 5, 5, 6, 6, 3, 2, 1};
int count = 0;
for(int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
if (numbers[i] == numbers[j])
{
count++;
}
}
printf("Number %d has occured %d many times \n", numbers[i], count);
count = 0;
}
}
只有我得到的输出如下:
Only the output I get is the following:
Number: 1 Occurence: 2
Number: 4 Occurence: 1
Number: 5 Occurence: 3
Number: 5 Occurence: 3
Number: 5 Occurence: 3
Number: 6 Occurence: 2
Number: 6 Occurence: 2
Number: 3 Occurence: 1
Number: 2 Occurence: 1
Number: 1 Occurence: 2
我只想计算每个数字的出现,似乎是在计算重复项.
I only want to count the occurrence of EACH digit, it seems to be counting duplicates.
如何纠正此代码?有人可以指出我正确的方向.
How can I correct this code? Can someone point me in the right direction.
非常感谢
阿隆索
推荐答案
请考虑以下修改的代码:
Consider this modified code:
#include <stdio.h>
#include <string.h>
int main()
{
int numbers [10]= {1, 4, 5, 5, 5, 6, 6, 3, 2, 1};
int count = 0;
for(int i = 0; i < 10; i++) { //i = current digit
for (int j = 0; j < 10; j++) { //j = index in array
if (i == numbers[j]) {
count++;
}
}
printf("Number %d has occured %d times \n", i, count);
count = 0;
}
}
输出:
Number 0 has occured 0 times
Number 1 has occured 2 times
Number 2 has occured 1 times
Number 3 has occured 1 times
Number 4 has occured 1 times
Number 5 has occured 3 times
Number 6 has occured 2 times
Number 7 has occured 0 times
Number 8 has occured 0 times
Number 9 has occured 0 times
您正在计算数组中每个数字出现的频率(包括数组中重复的数字).
You were counting how often each digit occuring in the array (including duplicate digits in the array) occured.
这篇关于计算字符串中数字出现的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文