gpt4 book ai didi

C 计算数组中重复元素的数量

转载 作者:行者123 更新时间:2023-11-30 18:50:48 26 4
gpt4 key购买 nike

该程序用于计算每个唯一元素出现的次数。输出为:

程序:

#include <stdio.h>
#include <stdlib.h>

int main()
{
int *input;
int n,c;

printf("Enter the number of elements in the array:");
scanf("%d",&n);

input = (int *) malloc(n*sizeof(int));

printf("Enter %d elements \n",n);
for(c=0; c<n; c++)
scanf("%d",input+c);//POINTER NOTATION

if (sizeof(input) == 0) return 0;

int prev = input[0];
int count = 1;
int i;
int ARRAYSIZE = sizeof(input) / sizeof(int);

for (i = 1; i < ARRAYSIZE; i++)
{

if (input[i] == prev)
{
count++;
}
else
{
printf("%d=%d ", prev, count);
prev = input[i];
count = 1;
}

}

printf("%d=%d\n", prev, count);
free(input);
return 0;
}

输入数组中元素的数量:10

输入 10 个元素

1 1 1 1 1 2 2 3 3 6

1=1

这里我输入了1(5次)、2(2次)、3(2次)和6(1次)但正如你所看到的,它只给出 1=1(1 次,但我已经输入 1 五次。)有人可以帮我吗?谢谢。

最佳答案

您不需要这个:

int ARRAYSIZE = sizeof(input) / sizeof(int);

使用n代替ARRAYSIZE

sizeof(input) 返回指针 input 的大小,而不是数组的大小。 for 循环不执行,输出来自外部 printf

关于C 计算数组中重复元素的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39026006/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com