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

扬·克里马泽夫斯基

我想执行else语句(True或Nothing)中的输出,但是由于某种原因,我的while循环仅执行if语句或else if语句。我知道我正在使用无限循环,但是我想通过使用else语句中两个语句之一中的break函数来离开它。我想要执行else语句,所以,他们有头发吗?-> Y->梅西?-> Y->是。还是他们有头发-> N->贝克汉姆?-> Y->是。还是他们有头发-> N-> Beckham-> N->什么都没有。还是有头发-> T-> Messi-> 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';
}
yaho为

您的while循环不会退出,因为if (yes)if(no)总是如此true

yesMessi所有非零值都称为true因此,您的yes值始终Messi具有保存位置的内存地址并且总是非零。
no也一样。no一直指向Beckham所以就是true

因此,我为您的逻辑修改了代码。请参考以下代码:

#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';
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章