到目前为止,我已设法找到重复的数字,但我想读入输入并确定列表中是否有任何重复的元素。如果所有值都是唯一的,则打印输出“list没有重复值”,否则打印出列表中从左到右显示的重复值(每个值由换行符分隔)。
我需要打印出列表中最重复的数字,然后是第二个重复的值。我该怎么做呢?我知道我必须编辑if语句,但我不确定如何。
#include <stdio.h>
#include <stdbool.h>
#define size 50
int main(void)
{
int i, j, n, du, dup[size];
bool copy = false;
scanf("%d", &n);
for (i=0; i<n; i++) {
scanf("%d", &dup[i]);
}
for (i=0; i<n; i++) {
for (j=0; j<n; j++) {
if (dup[i] == dup[j] && j!=i) {
copy = true;
}
}
}
if (copy) {
printf("list has duplicate values");
}
else {
printf("list has no duplicate values");
}
printf("\n");
return 0;
}
答案 0 :(得分:0)
#include <stdio.h>
#include <stdbool.h>
#define size 50
int intsort(int* val1,int *val2){
return (*val1<*val2)?-1:(*val1>*val2)?1:0;
}
int main(void)
{
int i, j, n, du, dup[size];
bool copy = false;
printf("number of elements: ");
scanf("%d", &n);
if(n<2) n=2;
if(n>50) n=50;
printf("enter elements:\n");
for (i=0; i<n; i++) {
printf("\t%d) ",i+1);
scanf("%d", &dup[i]);
}
j=0;i=0;
qsort(dup,n,sizeof(int),intsort);
printf("\n=========\n");
for(i=0;i<n;i++) printf(" %d",dup[i]);
printf("\n=========\n");
i=0;
while(i<(n-1)){
for(j=i+1;dup[i]==dup[j];j++);
copy=(i+1)<j;
if(copy){
printf("there are %d copies of %d \n",(j-i),dup[i]);
}
i=j;
}
if(!copy){
printf("No duplicated items \n");
}
printf("Done\n");
return 0;
}
答案 1 :(得分:0)
#include <stdio.h>
#include <stdbool.h>
#define size 50
typedef struct{
int value,dup;
}LIST_ENTRY;
/*______________________________________________________________
*/
int CompareEntries(LIST_ENTRY* val1,LIST_ENTRY *val2){
return (val1->dup>val2->dup)?-1:(val1->dup<val2->dup)?1:0;
}
/*______________________________________________________________
*/
int AddEntry(LIST_ENTRY * Entries,int val){
for(int i=0;i<size;i++){
if(Entries[i].value==val){
Entries[i].dup++;
return 1;
}
}
for(int i=0;i<size;i++){
if(Entries[i].dup==0){
Entries[i].value=val;
Entries[i].dup++;
return 0;
}
}
return 0;
}
/*______________________________________________________________
*/
void ClearEntries(LIST_ENTRY * Entries){
for(int i=0;i<size;i++){
Entries[i].value=0;
Entries[i].dup=0;
}
}
/*______________________________________________________________
*/
int main(void)
{
int i, d,n;
bool copy = false;
LIST_ENTRY Entries[size];
ClearEntries(Entries);
printf("number of elements: ");
scanf("%d", &n);
if(n<2) n=2;
if(n>50) n=50;
printf("enter elements:\n");
for (i=0; i<n; i++) {
printf("\t%d) ",i+1);
scanf("%d", &d);
copy|=AddEntry(Entries,d);
}
qsort(Entries,n,sizeof(LIST_ENTRY),CompareEntries);
printf("\n=========\n");
for(i=0;i<n;i++) {
if(Entries[i].dup){
printf("there are %d copies of %d\n",Entries[i].dup,Entries[i].value);
}
}
printf("\n=========\n");
if(!copy){
printf("No duplicated items \n");
}
printf("Done\n");
return 0;
}