I have a struct with an array of 100 int (b) and a variable of type int (a)
I have a function that checks if the value of "a" is in the array and i have generated the array elements and the variable with random values.
but it does开发者_Go百科n't work can someone help me fix it?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct {
int a;
int b[100];
} h;
int func(h v){
int i;
for (i=0;i<100;i++){
if(v.b[i]==v.a)
return 1;
else
return 0;
}
}
int main(int argc, char** argv)
{
h str;
srand(time(0));
int i;
for(i=0;0<100;i++){
str.b[i]=(rand() % 10) + 1;
}
str.a=(rand() % 10) + 1;
str.a=1;
printf("%d\n",func(str));
return 0;
}
Your check function returns after the first loop iteration. So unless the value you're looking for is the first element of the array, it returns 0 and never checks the rest of the array. The 'return 0' needs to be outside the body of the loop
for (i=0;i<100;i++){
if(v.b[i]==v.a)
return 1;
}
return 0;
Additionally, the for loop in main() checks to see if 0<100 (which will pretty much always be true...)
for(i=0;0<100;i++){
str.b[i]=(rand() % 10) + 1;
}
Should be:
for(i=0;i<100;i++){
str.b[i]=(rand() % 10) + 1;
}
Your loop:
for (i=0;i<100;i++){
if(v.b[i]==v.a)
return 1;
else
return 0;
}
should be:
for (i=0;i<100;i++){
if(v.b[i]==v.a)
return 1;
}
return 0;
so that you only fail after you have examined all the array entries. You might also want to pass your struct to the function using a pointer, to avoid the copying overhead.
Look at the else condition in the loop in func. Unless the item you are looking for is in the first position, it will never find it.
精彩评论