C语言菜鸟基础教程之条件判断
(一)if...else 先动手编写一个程序 #include <stdio.h> int main() { int x = -1; if(x > 0) { printf("x is a positive number!n"); } else { printf("x is not a positive number!n"); } return 0; } 运行结果:
程序分析: 定义一个整数x,并给他赋值。这个值要么大于0,要么不大于0(等于或小于0)。 这里建议不要再使用在线编译器,而是使用本机编译器(苹果电脑推荐Xcode,PC推荐dev C++)。在本机编译器上设置断点逐步执行,会发现if中的printf语句和else中的printf语句只会执行一个。这是因为if和else是互斥的关系,不可能都执行。 (二)if...else if...else 稍微改动程序 #include <stdio.h> int main() { int x = 0; if(x > 0) { printf("x is a positive number!n"); } else if(x == 0) { printf("x is zero!n"); } else { printf("x is a negative number!n"); } return 0; } 运行结果:
程序分析: 注意,x == 0,这里的等号是两个,而不是一个。 (三)多个else if的使用 #include <stdio.h> int main() { int x = 25; if(x < 0) { printf("x is less than 0n"); } if(x >= 0 && x <= 10) { printf("x belongs to 0~10n"); } else if(x >= 11 && x <= 20) { printf("x belongs to 11~20n"); } else if(x >= 21 && x <= 30) { printf("x belongs to 21~30n"); } else if(x >= 31 && x <= 40) { printf("x belongs to 31~40n"); } else { printf("x is greater than 40n"); } return 0; } 运行结果:
程序分析: (2) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |