[英]Find the frequency of each element in array in C
My task is to find frequency of each element, and elements are between 0 and 100. -1 for the end of input.我的任务是找到每个元素的频率,元素在 0 到 100 之间。-1 表示输入结束。
I have no problem with finding frequency, but there is some problem with my code, and I don't know what it is.我在查找频率方面没有问题,但是我的代码有一些问题,我不知道它是什么。 Probably with do-while loop.可能使用 do-while 循环。 I am beginner, and I hope you could help.我是初学者,希望对你有所帮助。
int main() {
int n = 0, i = 0, a[100], c;
int b[101] = {0};
do {
scanf("%d", &c);
if (c == -1)
break;
else if (c < 0 || c > 100)
printf("\nNumbers have to be between 0 i 100!\n");
else {
a[i] = c;
i++;
n++;
}
} while (c != -1);
n--;
for (i = 0; i < n; i++)
b[a[i]]++;
for (i = 0; i < n; i++) {
if (b[i] != 0)
printf("Count of %d is %d.\n", i, b[i]);
}
}
for (i=0;i<n;i++){
if (b[i]!=0)
printf("Count of %d is %d.\n", i, b[i]);
}
Here is an error in logic not syntax error but semantic error.这是逻辑错误,不是语法错误,而是语义错误。
You are supposed to display all the content of the b.您应该显示 b 的所有内容。 Since, B[] has the count of number.因为, B[] 有数量的计数。 But, the loop start from 0 and end with n(no. of data).但是,循环从 0 开始并以 n(数据数量)结束。
So, just make a change like this.所以,只要做出这样的改变。
for (i=0;i<101;i++){
if (b[i]!=0)
printf("Count of %d is %d.\n", i, b[i]);
}
And, the second thing is you don't need to decrease the value of n.而且,第二件事是您不需要减小 n 的值。
Just, Remove只是,删除
n--;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.