我有以下代码,我试图用它来显示整个数组中出现一定数量的代码的次数。我希望它打印出计算特定数量的次数。 (所有数字的范围均为0-20,索引为0 - 99)。
void count_frequency(int *number) {
int i;
int j;
int len = sizeof number / sizeof(int);
printf("%i\n", len);
printf("reached here");
for(i = 0; i < 99; i++){ //index{
int c = 0;
for(j = 0; j < 99; j++){
if(number[j] == number[i]){
c++;
}else{
continue;
}
}
printf("%i\n", c);
//printf("%i\n", number[i]);
}
}
int main(){
int i;
int table[MAX];
int len = sizeof table / sizeof(int);
printf("%ireached before loop\n", len);
for(i = 0; i < len; i++){
table[i] = random_in_range(0, 20);
}
count_frequency(table);
//printf("%i", sizeof(table) / sizeof(int));
return 0;
}
答案 0 :(得分:1)
int len = sizeof number / sizeof(int);
不会给你你所期待的。 number
是指针变量而不是数组。将您的功能更改为
void count_frequency(int *number, int len) {
int i;
int j;
int index[21] = {0};
printf("%i\n", len);
printf("reached here");
for(i = 0; i < len; i++){ //index{
index[number[i]%21]++;
}
for(i = 0; i < 21; i++)
printf("%d", index[i]);
}
你的函数调用应该是
count_frequency(table, len);
答案 1 :(得分:1)
你在这里。老实说,你的代码中有一些神奇的想法。这有效 - 它不是“最好的”,而是对你所拥有的东西的改进。如果不清楚,请告诉我。我对rand_in_range
的定义并不完全准确 - 它会略微偏向较低的数字。
include <stdio.h>
#include <stdlib.h>
#define MAX 100
#define random_in_range(a,b) ( rand() % ((b) - (a) + 1) + (a) )
void count_frequency(int *table, int *output, int n1, int n2) {
// n1 = number of elements in table
// n2 = number of elements in output
int i;
// int len = sizeof number / sizeof(int); <<<< meaningless!
// printf("%i\n", len);
// printf("reached here");
for(i = 0; i < n1; i++) { // loop over the elements in the table
output[table[i] %n 2]++; // using % n2 so we don't go outside bounds of array.
}
}
int main(){
int i;
int table[MAX];
int counts[21]={0}; // <<<< need a place to put the result
int len = sizeof table / sizeof(int);
for(i = 0; i < len; i++){
table[i] = random_in_range(0, 20);
}
count_frequency(table, counts, MAX, 21);
for(i = 0; i < 21; i++) {
printf("number %d - frequency %d\n", i, counts[i]);
}
return 0;
}
输出:
number 0 - frequency 3
number 1 - frequency 5
number 2 - frequency 3
number 3 - frequency 6
number 4 - frequency 6
number 5 - frequency 7
number 6 - frequency 3
number 7 - frequency 5
number 8 - frequency 6
number 9 - frequency 9
number 10 - frequency 4
number 11 - frequency 2
number 12 - frequency 6
number 13 - frequency 8
number 14 - frequency 3
number 15 - frequency 4
number 16 - frequency 5
number 17 - frequency 6
number 18 - frequency 6
number 19 - frequency 3
number 20 - frequency 0
答案 2 :(得分:0)
所以你说你有一个包含100个数字的数组,每个数字的范围是0-20,你想计算该数组中单个数字的出现次数吗?那应该这样做:
size_t count_occurrences(int interesting_num, int* array, size_t array_size) {
size_t i, occurrences = 0;
for (i=0; i < array_size; ++i) {
if (array[array_size] == interesting_num) {
++occurrences;
}
}
return occurrences;
}
从技术上讲,您可以使用无符号字符替换那些“size_t”,对于您正在讨论的数字范围,但考虑到您尝试的len的动态计算,以及使用“MAX”,我怀疑您可能想在某个时候增加这些范围。所以,我在更安全,更通用的实施方面犯了错误。