gpt4 book ai didi

c - 数组中没有重复值

转载 作者:行者123 更新时间:2023-11-30 21:27:14 27 4
gpt4 key购买 nike

我需要编写一个在数组内存储数字的程序。但它不能有重复的元素。

  int x;
int z[8];

for( x = 0; x<8;x++)
printf("number: ");
scanf("%d",&z[x]);
}

for( x=0;x<8;x++) {
printf("%d ",z[x]);
}

最佳答案

首先,初始化数组,这样您就不会最终读取未初始化的值并导致测试失败。

int user_nums[6] = {0};

接下来,您需要在 for 循环中进行另一次检查,以再次读取该数字是否重复。

代码将如下所示。

#include<stdio.h>
int main(){
int x,y;
int exists = 0;
int user_nums[6] = {0};
for( x = 0; x<6;x++){//for loop to get the players selected numbers

do {
exists = 0;
printf("Enter a number(from the #'s 1-42): ");
scanf("%d",&user_nums[x]);

for(y =0; y < x; y++) { //to check for duplicates
if (user_nums[x] == user_nums[y])
{
printf("Number already exists\n ");
exists = 1;
break;
}
}

}while (user_nums[x]<1 || user_nums[x]>42 || exists);//accepts only numbers from 1-42 which are not duplicates (continous to ask you for a number until condition is met).
}

printf("Your numbers: \n");

for( x=0;x<6;x++){
printf("%d ",user_nums[x]); // prints the numbers you inputed.
}

return 0;
}

关于c - 数组中没有重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53080187/

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