C 如何在while循环的条件下与多个值进行比较
我有一个C 如何在while循环的条件下与多个值进行比较,c,loops,C,Loops,我有一个structs数组,其中填充了一些值。我正在提示用户输入一个值。然后我需要检查数组,看看用户输入的值是否包含在数组中。 如果找到,则程序将继续执行。 如果未找到,则程序将提示用户输入其他值 下面是我已经编写的代码。您可以看到,我已尝试作为do while循环条件的一部分扫描阵列,但这不起作用 do { printf("Insert the number you want to search:\n"); numero = getInputFromUser(); } wh
structs
数组,其中填充了一些值。我正在提示用户输入一个值。然后我需要检查数组,看看用户输入的值是否包含在数组中。如果找到,则程序将继续执行。
如果未找到,则程序将提示用户输入其他值 下面是我已经编写的代码。您可以看到,我已尝试作为do while循环条件的一部分扫描阵列,但这不起作用
do
{
printf("Insert the number you want to search:\n");
numero = getInputFromUser();
} while (for (i = 0; i < numAlunos; i++) // This is where I need help
numero != vAlunos[i].numero)
do
{
printf(“插入要搜索的号码:\n”);
numero=getInputFromUser();
}while(对于(i=0;i
如何将数组作为循环条件的一部分进行扫描?如果使用C99,则可以访问stdbool.h并可以使用布尔类型,如果没有,只需根据您用作
bool
替换的任何内容(如typedef、#define)对其进行适当调整,或者仅返回0和1以及int
我还假设您的结构数组和数组长度变量是全局的,但是如果它们不是全局的,您可以修改这个函数将它们作为参数传入
bool checkForValue(int numeroToSearch) // Guessing int, but change as needed
{
int i;
for (i = 0; i < numAlunos; i++)
{
if(numeroToSearch == vAlunos[i].numero)
{
return true;
}
}
return false;
}
如果您不介意使用编译器扩展,那么GCC和Clang都提供了可以嵌入到条件中的:
do {
printf("Insert the number you want to search:\n");
numero = getInputFromUser();
} while (({
int i = 0;
while(i < numAlunos && vAlunos[i] != numero)
++i;
i == numAlunos; // "return value" of the statement-expressions
}));
do{
printf(“插入要搜索的号码:\n”);
numero=getInputFromUser();
}当(({
int i=0;
而(i
编写一个新函数,执行搜索并返回是否找到。然后,您可以在while循环条件下使用该函数。我已尝试改写您的问题并清理代码,以便将其集中在您提到的问题上。如果我没有正确地清理它,请随意进一步编辑它或展开我所做的。我明白你所说的一切,除了一件事:我如何才能获得“numeroToSearch”以便在checkForValue函数中使用它?我必须从使用循环的函数返回它,对吗?I@NelsonSilva-将其传递给函数。如果您查看我发布的do-while循环代码,您会看到我正在传递
numero
。我只是在函数中调用了它numerotsearch
,以明确它是什么。我添加的do-while循环直接取自您的示例代码,我所做的唯一一件事就是使用do-while条件中列出的for循环,并将其移动到一个函数,然后我从do-while条件调用了该函数。
do {
printf("Insert the number you want to search:\n");
numero = getInputFromUser();
} while (({
int i = 0;
while(i < numAlunos && vAlunos[i] != numero)
++i;
i == numAlunos; // "return value" of the statement-expressions
}));