gpt4 book ai didi

c - 检测数组中的数是否已经输入(C程序)

转载 作者:太空宇宙 更新时间:2023-11-04 04:40:25 26 4
gpt4 key购买 nike

我有点迷茫。我想编写一个程序,如果数组中的数字已经输入,那么它会检测到它并说它重复了,所以程序会告诉用户输入另一个非重复的整数。

#include <stdio.h>
#define SIZE 5

int main()
{
int array[SIZE];
int i;
int j;


for (i = 0; i < SIZE; i++)
{
printf("[%d] Insert a number: ", i + 1);
scanf("%d", &array[i]);

j = i - 1; // This is the closest that I've gotten guys. But I need to create a loop to make j be -1 until it finds a repeated number in the array.

if (array[i] == array[j])
{
printf("The number is repeated");
i--;
}

if (array[i] > 1000)
{
printf("Sorry, the number you entered cannot be bigger than 1000\n");
i--;
}

if (array[i] < 0)
{
printf("Sorry, the number you entered cannot be less than 0\n");
i--;
}
}

for (i = 0; i < SIZE; i++)
{
printf("The array inside is %d\n", array[i]);
}


return 0;
}

如您所见,我做了类似的事情。我只是把 j = i - 1 所以基本上它会告诉程序它被重复了。但是,我想我应该创建一个循环,将 -1 减去 j 直到它找到重复值(如果有的话)。我只是不知道如何创建该循环并使其工作。

非常感谢!

最佳答案

可以通过以下方式进行检查(无需测试)

int array[SIZE];
int i;


for (i = 0; i < SIZE; i++)
{
int valid = 1;
int num;

do
{

printf("[%d] Insert a number: ", i + 1);
scanf("%d", &num );

if ( !( valid = !( num > 1000 ) ) )
{
printf("Sorry, the number you entered cannot be bigger than 1000\n");
}
else if ( !( valid = !( num < 0 ) ) )
{
printf("Sorry, the number you entered cannot be less than 0\n");
}
else
{
int j = 0;
while ( j < i && num != array[j] ) j++;

if ( !( valid = j == i ) )
{
printf("The number is repeated");
}
}
} while ( !valid );

array[i] = num;
}

关于c - 检测数组中的数是否已经输入(C程序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27081147/

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