所以我试图计算一个数组中每个数字的出现次数。
我到目前为止的代码如下所示:
#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;
}
}
只有我得到的输出如下:
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
我只想计算每个数字的出现次数,似乎是在计算重复数。
如何更正此代码?有人能指出我正确的方向。
非常感谢
阿隆索
答案 0 :(得分:1)
考虑这个修改后的代码:
#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
您正在计算阵列中每个数字出现的频率(包括数组中的重复数字)。
答案 1 :(得分:0)
您将需要数组 - 一个用于计数(结果),另一个用于输入。循环输入数字时,应该在count数组中递增索引。我无法抗拒实际编写代码,所以,你去,以下应该工作 IN C ++
#include <stdio.h>
#include <string.h>
int main()
{
int inputNumbers [] = {1, 4, 5, 5, 5, 6, 6, 3, 2, 1};
int resultCount [] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
int countNumbers = sizeof(inputNumbers) / sizeof(inputNumbers[0]);
for(int i = 0; i < countNumbers; i++)
{
resultCount[inputNumbers[i]]++;
}
for(int i = 0; i < countNumbers; i++)
{
printf("Number %d has occured %d times \n", i, resultCount[i]);
}
}
希望有所帮助。