用于查找重复整数的数组问题

时间:2016-10-09 09:39:18

标签: c arrays function boolean scanf

我目前正在进行编程练习(特别是使用C编程),我正在尝试一个章节末尾的问题,这个问题有这样的描述:

“使用单下标数组来解决以下问题。 读入20个数字,每个数字在10到100之间,包括10和100。 读取每个数字,打印 只有当它不是已读过的数字的副本时才会出现。提供所有20个“最坏情况” 数字是不同的。使用尽可能小的数组来解决这个问题“

这是我到目前为止所做的:

#include <stdio.h>
#include <stdbool.h> //used this library for the ability to use true and false
#define SIZE 20

bool searchArray(int integer, unsigned int j); //prototype for the searchArray function

int main (void)
{

bool print;
int numbers[20];
unsigned int i; 

for (i = 0; i < SIZE; i++)
{   
    scanf("%d", &numbers[i]);
    print = searchArray(numbers[i], i); //receives true or false

    if (print == true)
    {
        printf("\nNumber at element %d: %d\n", i, numbers[i]);
    }
    else if (print == false)
    {
        printf("\nThis element has a copy in the array already\n");
    }



}

}


bool searchArray(int integer, unsigned int j) //function that helps decide whether or not to print out the integer
{
static int numberscopy[20];
unsigned int n;


numberscopy[j] = integer;

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

        if (numberscopy[n] == numberscopy[j] && n != j) // for making sure that the inputted integer is equal to any element that's currently in the array and making sure it's not including the very same integer that was just input on it's first appearance
        {
            return false;
        }
    return true;
}

}

解释:我在这个程序中所做的是我定义了一个名为searchArray的函数,它基于当前数组元素的输入和数组索引返回一个布尔值(true或false)。在main函数的for循环中,我使用scanf一次一个地从用户接收整数。每个整数元素都放在一个名为“numbers”的数组中的数组索引中。

然后,数组元素和程序所在的数组的当前索引都被放入searchArray函数中。在searchArray函数中,每个元素都被输入到函数的本地20元素数组中,称为“numberscopy”(在该数组中,每个数字都放在其中,它基于传递给searchArray的i的当前值)。然后在searchArray函数中,有一个for循环,它搜索numberscopy数组中的所有当前元素,并检查刚刚放入的整数是否已经在numberscopy数组中。如果找到,则返回“false”。如果没有,则会自动返回“true”。

我认为这样可行,但问题是它似乎只能检测每次运行时输入的第一个整数的重复项。例如,如果先输入一个数字25,然后再输入一个32,那么再次输入25然后再输入一个32,它会在我第二次输入25时正确检测到25已经在数组中,但对于32 ,它似乎没有检测到它并在再次放入时打印32。 The example here

任何人都知道为什么这不像我想的那样工作?

1 个答案:

答案 0 :(得分:0)

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

        if (numberscopy[n] == numberscopy[j] && n != j) 
        {
            return false;
        }

}
        return true;
}

而不是

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

        if (numberscopy[n] == numberscopy[j] && n != j)
        {
            return false;
        }
    return true;
}

}