我在將此程式更改為 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;
}
uj5u.com熱心網友回復:
您可以將 break 陳述句添加到 for 回圈中,如下所示:
for (i = 0; i <= 4; i )
if (strcmp(target_name, name[i]) == 0) {
position = i;
break;
}
或者您也可以使用中斷或如下條件進行 while 回圈:
while (position == -1){//do stuff}
這樣當您在陣列中找到元素時,就不會再次進入回圈。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/329906.html
