0

如何使用 C 语言将一个整数与一个由十个整数组成的数组进行比较,以找出单个整数是否包含在数组中?如果原始问题不清楚,我深表歉意,而滑动等于我想输出 PORTD=0b10000000 的数组中的任何数字。谢谢!

short a[10]={10, 11, 12, 13, 14, 15, 16, 17, 18, 19}; //Array of accepted passwords.
short array[10];
int i;
for(i=0; i<10; i++){
    array[i]=a[i];
}

srand(clock());

while(1){
int swipe=rand() % 20; /* Simulated code read from card swipe, in this
                        * instance we used a random number between
                        * 1 and 20.*/
for(i=0; i<10; i++){    
    if(swipe == array[i]) {
        PORTD=0b10000000;
    } else {
        PORTD=0b00001000;
    } //If swiped code evaluates as one of the approved codes then set PORTD RD7 as high.
}

char Master=PORTDbits.RD7;

这似乎已经解决了......感谢您的所有帮助!

for(i=0; i<10; i++){    
if(swipe == array[i]) {
    PORTD=0b10000000;
    break;
} else {
    PORTD=0b00001000;
    }
}
4

4 回答 4

1

您需要根据您接受的密码数组中的所有十个值来测试您的刷卡值。

例如如下

for(i=0; i<10; i++)
  if(swipe == array[i]) {
    set a true flag (and maybe exit the for loop)
  }
Depending on the flag, set the output
于 2016-03-02T20:07:06.693 回答
0

if(swipe == a[i]). 这会调用未定义的行为,因为i10 和 10 是越界索引。有效索引从 0 到 9。

于 2016-03-02T19:57:16.957 回答
0

除了@kaylum的回答...

因为是循环调用,所以进入循环前 rand()需要先调用,srand()

srand(clock());//for example
while(1){
    LATD=0x00;
    int swipe=rand() % 20;
    ...   

如果不这样做,每次执行时获得的随机数将是相同的值序列。

此外,如果i在用于比较之前未重新初始化,则为 == 10。在用作数组索引之前需要对其进行重置...

此外,在您的代码中,您似乎想根据 10 个接受的密码检查最新的随机数。如果这是正确的,您必须比较所有 10 个:

int main(void)
{
    srand(clock());//for example
    j = 0;
    while(1)
    {
        int swipe=rand() % 20;
        PORTD=0b00000000;
        for(i=0;i<10;i++)
        {
            j++;
            if(swipe == array[i]) 
            {
                PORTD=0b10000000;
                break;
            } 

        }
        //to show ratio of legal to illegal passcodes...
        printf("times through: %d  Value of PORTD %d\n", j, PORTD);
    }
}
于 2016-03-02T19:57:50.270 回答
0

您正在尝试模拟随机读卡操作并在不同情况下同时获得通过/失败。使用 1 到 20 之间的滑动值和仅在 10、19 范围内的密码,您希望查看某些实例是否失败。那是对的吗?

如果是这样,考虑到您的 rand() 函数仅返回整数,请设置断点并探测滑动值。它似乎总是具有相同的价值。使 rand() 函数更好地用于更广泛的统计分布。有许多来源可以生成随机整数,例如线性同余法等。

此外,应该为数组的每个值循环比较。

于 2016-03-02T21:00:00.360 回答