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

时间:2014-11-22 18:51:05

标签: c arrays repeat

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

#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,直到找到重复的值(如果有的话)。我只是不知道如何创建该循环并使其工作。

非常感谢!

2 个答案:

答案 0 :(得分:0)

这应该适合你:

#include <stdio.h>

#define SIZE 5

int main() {

    int array[SIZE];
    int numberCount, repeatCount;


    for(numberCount = 0; numberCount < SIZE; numberCount++) {

        printf("[%d] Insert a number:\n>", numberCount + 1);
        scanf("%d", &array[numberCount]);

        for(repeatCount = 0; repeatCount < numberCount; repeatCount++) {
            if (array[numberCount] == array[repeatCount]) {
                printf("\nThe numbe is repeated\n");
                numberCount--;
                break;
            }
        }

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

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

    }

    printf("\n\n");

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

    return 0;
}

答案 1 :(得分:0)

检查可以通过以下方式完成(无需测试)

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;
}