繁体   English   中英

将for循环程序修改为while循环程序的问题

[英]Problem of modify a for loop program into a while loop program

我在将此程序更改为 while 循环而不要求程序运行 4 次时遇到问题,有人告诉我,如果程序在数组中找到目标名称后结束而不是运行 4 次会更合理,我有noidea 如何在此程序中实现 while 循环而不运行 4 次而不是在匹配数组中的名称后结束。 请帮帮我,谢谢,我已经在谷歌上检查过了,我对此不太了解。

For循环代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char *name[] = {"Peter", "Mary", "John", "Bob", "Kathy"};
    char target_name[10];
    int i, position;

    printf("Enter a name to be searched: ");
    scanf("%s", &target_name);

    position = -1;
    for (i = 0; i <= 4; i++)
        if (strcmp(target_name, name[i]) == 0)
           position = i;

    if (position >= 0)
       printf("%s matches the name at index %d of the array.\n", target_name, position);
    else
       printf("%s is not found in the array.", target_name);

    return 0;
}

While 循环代码(有人告诉我不运行 4 次更合理):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char *name[] = {"Peter", "Mary", "John", "Bob", "Kathy"};
    char target_name[10],decision;
    int i, position;

    printf("Enter a name to be searched: ");
    scanf("%s", &target_name);
    i = 0,
    position = -1;
    while ( i <= 4) {
        if (strcmp(target_name, name[i]) == 0)
           position = i;
           i++;
}
    if (position >= 0)
       printf("%s matches the name at index %d of the array.\n", target_name, position);
    else
       printf("%s is not found in the array.", target_name);

    return 0;

}

您可以将 break 语句添加到 for 循环中,如下所示:

for (i = 0; i <= 4; i++)
    if (strcmp(target_name, name[i]) == 0) {
        position = i;
        break;
    }

或者您也可以使用中断或如下条件进行 while 循环:

while (position == -1){//do stuff}

这样当您在数组中找到元素时,就不会再次进入循环。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM