gpt4 book ai didi

c - 为什么 while 循环在 else 语句之前停止?

转载 作者:行者123 更新时间:2023-11-30 14:38:27 25 4
gpt4 key购买 nike

我想执行 else 语句中的输出(True 或 Nothing),但由于某种原因,我的 while 循环仅执行第一个 if 语句或 else if。我知道我正在使用无限循环,但我想通过使用两个 else 语句之一中的 Break 函数来离开它。我想要的是执行else语句,那么,他们有头发吗? ->Y -> 梅西? -> Y-> 正确。或者他们有头发吗 -> N -> 贝克汉姆? -> Y -> 正确。或者他们有头发吗 -> N -> 贝克汉姆 ->N -> 什么都没有。或者他们有头发吗 -> T->梅西->N->什么都没有

#include <stdio.h>
#include <strings.h>



int random(char z[]);


int main() {

char *x ="Do they have hair";
char *yes = "Messi";
char *no = "Beckham";
char *u ="Nope";


do {
char *currents = x;
while (1) {
if (random(currents)) {
if (yes) {
currents = yes;
printf("First check\n");
} else {
printf("True: %s\n", yes);
break;
}

} else if (no) {
currents = no;
printf("False\n");

} else {
printf("Nothing\n");
break;
}
}
}while(random("Run Again?"));
return 0;
}
int random(char z[])
{
char a[3];
printf("%s: %s",z,a);
fgets(a, 3,stdin);

return a[0] == 'y';
}

最佳答案

您的 while 循环不会退出,因为 if (yes)if(no) 始终为 true.

梅西。所有非零值都被引用为true。因此,您的 yes 值始终是保存 Messi 的内存地址。并且它总是非零。
no 也一样。 no 始终指向Beckham。所以,这是正确

所以,我根据你的逻辑修改了代码。请引用以下代码:

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

int random(char z[]);
int main() {

char x[] = "Do they have hair";
char again[] = "run again";
char yes[] = "Messi";
char no[] = "Beckham";
char u[] = "Nope";

do {
if (random(x)) {
if (random(yes)) printf("True!\n");
else printf("Nothing!\n");
}
else {
if (random(no)) printf("True!\n");
else printf("Nothing!\n");
}
} while (random(again));
return 0;
}
int random(char z[])
{
char a[3];
printf("%s?:", z);
fgets(a, 3, stdin);

return a[0] == 'y';
}

关于c - 为什么 while 循环在 else 语句之前停止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56606660/

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