while 循环不会以逻辑条件终止 [英] while loop won't terminate with a logical conditional

查看:29
本文介绍了while 循环不会以逻辑条件终止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我添加 OR 条件语句,此循环将不会终止.如果一个是假的,那么它应该终止.

This loop won't terminate if I add an OR conditional statement. If one is false, then it should terminate.

//全局变量

int x = 100;
    char *n= malloc (64);

void add(void)
{       

    do      
    {
        printf("Would you like to add 1? (y/n) ");
        fgets(n, 64, stdin);
            //removes newline
        n[strlen(n)-1] = '';
            x++;
    }       
//if I add || (x!=100) it keeps looping me even if I press "n"
//otherwise without it it works fine

        while((strncmp(n, "n", 1) != 0) || x!=100 );

        free(n);
}

推荐答案

在循环的底部,您正在执行 x++.一旦你遇到 while 条件,x == 101,所以你的循环永远不会终止,x 在条件被检查时永远不会等于 100.

At the bottom of your loop, you're doing x++. Once you hit the while condition, x == 101, so your loop never terminates, x never equals 100 when the condition is being checked.

也许你想要:

while((strncmp(n, "n", 1) != 0) && x != 100);

如果两个条件中的任何一个为假,哪个将终止循环.

Which would terminated the loop if either of the two conditions is false.

&& 是逻辑与"运算符,|| 是逻辑或"运算符.为了帮助您进行跟踪,您可以使用真值表来帮助您理清细节.逻辑和与逻辑合取和逻辑或与逻辑析取相同.

&& is the 'logical and' operator, || is the 'logical or' operator. To help you keep track, you can use a Truth Table to help you sort out the details. Logical and is the same as logical conjunction and logical or is the same as logical disjunction.

这篇关于while 循环不会以逻辑条件终止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆