小朋友学C语言(12):判断

本文通过几个示例程序详细解析了C语言中的条件判断逻辑,包括如何处理非0值、布尔表达式的值以及字符变量在条件判断中的表现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

(一)

先动手编写一个程序:

#include <stdio.h>

int main()
{
    if(1)
    {
        printf("The condition is true!\n");
    }

    return 0;
}

运行结果:

The condition is true!

再把1依次改为,2,5,100,-10,发现运行结果完全一样。
再改成if(0),此时发现没有运行结果,说明printf()语句没被执行。

C语言把判断语句中的任何非0或非空的值当作真。所以if(1), if(2), if(5), if(100), if(-10)的效果是一样的。

(二)

再编写一个程序:

#include <stdio.h>

int main()
{
    int a = 100;
    if(a > 0)
    {
        printf("The condition value is %d\n", (a > 0));
    }

    return 0;
}

运行结果:

The condition value is 1

分析:
a = 100,a > 0成立 ,所以if( a > 0)等价于if(1)。
在C语言中,判断语句是有值的,要么为1,要么为0。比如本程序中a > 0的值就是1。

(三)

最后编写一个程序:

#include <stdio.h>

int main()
{
    char c1 = '\0';
    if(c1)
    {
        printf("The condition is true!\n");
    }
    else
    {
        printf("The condition is false!\n");
    }

    char c2 = ' ';
    if(c2)
    {
        printf("The condition is true!\n");
    }
    else
    {
        printf("The condition is false!\n");
    }

    char c3 = 'A';
    if(c3)
    {
        printf("The condition is true!\n");
    }
    else
    {
        printf("The condition is false!\n");
    }

    return 0;
}

运行结果:

The condition is false!
The condition is true!
The condition is true!

说明:C语言中用’\0’来表示空字符。空格’ ‘也是一个字符,这从if(c2)条件为真就可以看出来。

(四)作业

在纸上默写(三)中的程序。

更多内容请关注微信公众号
wchat_official.jpg

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值