gpt4 book ai didi

c - 带 IF 语句的 For 循环 C 编程

转载 作者:行者123 更新时间:2023-11-30 21:19:55 25 4
gpt4 key购买 nike

char userChoice;

printf("Choose how you would like to search.\nEnter A to display all players information.\
\nEnter N to search a player based on name.\nEnter J to search a player based on jersey number.\
\nEnter P to search a player based on position.\nEnter your choice: ");
scanf("%c", &userChoice);

do
{
if (userChoice == 'A' || userChoice == 'a')
{
for (index = 0; index < count; index = index + 1)
{
displayPlayers(&players[index]);
}
}

if (userChoice == 'J' || userChoice == 'j')
{
int jerseyNumber;

printf("\nEnter jersey number for the player: ");
scanf("%i", &jerseyNumber);

for (index = 0; index <= MAX_PLAYERS; index++)
{
if (jerseyNumber == players[index].jerseyNumber)
{
// If the condition is met the singleDisplay function is called.
// Containing the array of struct
singleDisplay(&players[index]);

}
}
}
if (userChoice == 'N' || userChoice == 'n')
{
char playerName[LEN_NAME + 1];

printf("\nEnter name for the player: ");
scanf("%s", playerName);

for (index = 0; index <= MAX_PLAYERS; index++)
{
if (strcmp(playerName, players[index].firstName) == 0)
{
singleDisplay(&players[index]);

}
}
}

这段代码的大部分只是为了上下文,我遇到的问题是无法做出一个 else 语句来向用户输出一条消息,表明他们输入的 Jersey 没有找到。问题是 else 语句位于循环内部,并且在比较数组中的所有数字时,无论多次都会打印其消息。

最佳答案

您发布的代码中唯一相关的部分是:

    for (index = 0; index <= MAX_PLAYERS; index++)
{
if (jerseyNumber == players[index].jerseyNumber)
{
singleDisplay(&players[index]);
}
}

您的问题唯一相关的部分是:

an else statement that outputs a message to user that jersey they entered was not found. The problem is the else statements is inside the loop and will print its message no matter what multiple times, while it is comparing all numbers in array.

好的,这样就清楚了。您一定尝试过这样的代码(但未能向我们展示):

    for (index = 0; index <= MAX_PLAYERS; index++)
{
if (jerseyNumber == players[index].jerseyNumber)
{
singleDisplay(&players[index]);
}
else
{
printf("no match for jersey number\n");
}
}

当然,错误消息将被打印 MAX_PLAYERS 次,或者如果被发现的话,可能会被打印 MAX_PLAYERS - 1 次。因此,您需要修改代码以明确避免这种情况:

    int found = 0;
for (index = 0; index <= MAX_PLAYERS; index++)
{
if (jerseyNumber == players[index].jerseyNumber)
{
singleDisplay(&players[index]);
found++;
break;
}
}
if (!found)
{
printf("no match for jersey number\n");
}

这里的break是可选的,但它是一种很好的形式,因为它可以避免在您找到匹配项后检查更多数字。也就是说,除非您想支持多个球员拥有相同的 Jersey 号码,在这种情况下请删除 break

关于c - 带 IF 语句的 For 循环 C 编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45249557/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com