计算数组-C中重复元素的数量
从一个大小n的数组中获取用户的输入,并打印重复元素的总数(发生两次或更多次的元素)。
输入格式:第一行包含N。第二行包含由空间隔开的N正整数。
输出格式:重复元素的计数。
我编写的程序仅针对两个相同的元素,并且未能读取超过2个重复。
#include<stdio.h>
#include <stdlib.h>
int main()
{
int arr[1000],i,j,n,count=0;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(arr[i]==arr[j])
{
count=count+1;
break;
}
}
}
printf("%d",count);
}
输入(对于八位数的示例):
1 2 3 1 2 1 5 6
此代码的输出不正确:
3
预期输出为2,具有重复项的元素计数(1具有两个重复项,2个重复)。
所以请解释一下在做什么错?
Take a input from user in an Array of a size N and print the total number of duplicate elements (The elements which occur two or more times).
Input Format: The first line contains N. The second line contains the N positive integer separated by a space.
Output Format: Count of duplicate elements.
The program I wrote works for only two same elements and fails to read more than 2 duplicates.
#include<stdio.h>
#include <stdlib.h>
int main()
{
int arr[1000],i,j,n,count=0;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(arr[i]==arr[j])
{
count=count+1;
break;
}
}
}
printf("%d",count);
}
Input (for an eight-digit example):
1 2 3 1 2 1 5 6
Incorrect output of this code:
3
The expected output is 2, the count of elements which has duplicates (1 has two duplicates and 2 has one duplicate).
So please explain what am doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用以下代码进行相同的代码。它首先分为数组:
您可以在这里找到它
You can use following code for the same. It first sorts the array:
You can find it working here
当
i == 0&amp;&amp; j == 4
,i == 0&amp; j == 6
再次增加时,您的计数会增加。 4&amp; j == 6 。当第三个检查是多余的。因此,要解决i&lt; j
条件,并休息以停止检查已经检查的元素。Your count increase when
i==0&&j==4
,i==0&&j==6
and again ati==4&j==6
. When the third check is redundant. So to resolve that put in ai<j
condition and break to stop checking the already checked elements.以下Java程序花费的时间更少,并且非常灵活,请根据X数组中的数字增加Y数组的大小。
The below java program takes less time and it is very flexible, increase the y array size based on the number in x array.
您可以使用此代码,它将编写-1代替元素的所有重复项,因此它将计算仅具有重复项的元素。
You can use this code, It will write -1 in place of all the duplicates of an element and hence it will count the elements having duplicates only once.