C语言 计算整数数组中不同值的数量?

完成count_Udistinct_Uvalues()函数,计算整数数组中不同值的数量
如果需要,可以添加自己的函数
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

int count_distinct_values(int * values) {
\\补全
return 0;
}
int main(void) {
int test_values[] = { 1, 2, 1, 2, 1, 3, 4, 5, 4, 7, -1};
int *rand_values = test_values;
int test_case = 1;

srand(10);
scanf("%d", &test_case);
\\补全
printf("# of distinct values = %d\n", count_distinct_values(rand_values));

if (test_case > 1)
free(rand_values);

return 0;
}

输入1 输出# of distinct values = 6
最新回答
思慕

2026-10-21 20:13:55

用C语言统计一个数组中不同元素重复的个数:

public class Test {

public int count(int[] array) {

int len = array.length;

for (int i = 0; i< array.length - 1; i++) {

for (int j = i + 1; j< array.length; j++) {

int num = array[i];

if (array[j] == num) {

// 重复,数组总长度减1

len--;

i++;

}

}

}

return len;

}

public static void main(String[] args) {

// 测试数据:总共是9个不同的元素,按照升序排好,其中有重复出现的元素。

int[] array = new int[] { 1, 1, 2, 2, 2, 3, 4, 5, 5, 6, 7, 7, 8, 9 };

System.out.println(new Test().count(array));

}

}

扩展资料:

C程序中函数特性

C程序中函数的数目实际上是不限的,一个C程序中必须至少有一个函数,而且其中必须有一个并且仅有一个以main为名的函数,这个函数称为

主函数
,整个程序从这个主函数开始执行。

函数内部究竟是如何工作的,外部程序是不知道的。外部程序所知道的仅限于输入给函数什么以及函数输出什么。函数提供了编制程序的手段,使之容易读、写、理解、排除错误、修改和维护。

参考资料来源:百度百科—

c语言