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

骑猪看日落 2022-06-07 12:51 280阅读 0赞

(一)

先动手编写一个程序:

  1. #include <stdio.h>
  2. int main()
  3. {
  4. if(1)
  5. {
  6. printf("The condition is true!\n");
  7. }
  8. return 0;
  9. }

运行结果:

  1. The condition is true!

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

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

(二)

再编写一个程序:

  1. #include <stdio.h>
  2. int main()
  3. {
  4. int a = 100;
  5. if(a > 0)
  6. {
  7. printf("The condition value is %d\n", (a > 0));
  8. }
  9. return 0;
  10. }

运行结果:

  1. The condition value is 1

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

(三)

最后编写一个程序:

  1. #include <stdio.h>
  2. int main()
  3. {
  4. char c1 = '\0';
  5. if(c1)
  6. {
  7. printf("The condition is true!\n");
  8. }
  9. else
  10. {
  11. printf("The condition is false!\n");
  12. }
  13. char c2 = ' ';
  14. if(c2)
  15. {
  16. printf("The condition is true!\n");
  17. }
  18. else
  19. {
  20. printf("The condition is false!\n");
  21. }
  22. char c3 = 'A';
  23. if(c3)
  24. {
  25. printf("The condition is true!\n");
  26. }
  27. else
  28. {
  29. printf("The condition is false!\n");
  30. }
  31. return 0;
  32. }

运行结果:

  1. The condition is false!
  2. The condition is true!
  3. The condition is true!

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

(四)作业

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

更多内容请关注微信公众号
wchat\_official.jpg

发表评论

表情:
评论列表 (有 0 条评论,280人围观)

还没有评论,来说两句吧...

相关阅读

    相关 小朋友C语言(20):数组

    一、数组简介 C 语言支持数组数据结构,它可以存储一个固定大小的相同类型元素的顺序集合。数组是用来存储一系列数据,但它往往被认为是一系列相同类型的变量。 数组的声明并