C语言学习之路--第三站 判断与循环

36 阅读2分钟

学过一些代码的应该都知道判断与循环在写代码中的重要性。判断和循环是非常重要的一环,需要理解并且灵活运用。

其内容与Java类似,因此对于我个人而言要进行一遍实践。在实践中发现与Java的不同之处。

首先是判断语句,常见的有 if / if...else / 嵌套if / switch / 嵌套switch 等。介于有一定的基础,因此直接实践嵌套。

	int h = 7;

if (h < 5) 
{
	printf("判断1\n");
}
else
{
	printf("判断2\n");
}

if (h>5)
{
	if (h < 8) 
	{
		printf("判断3\n");
	}
	else
	{
		printf("判断4\n");
	}
}
else
{
	printf("判断5\n");
}

switch (h)
{
case 3:
	printf("h=3\n");
	break;
case 4:
	printf("h=4\n");
	break;
case 5:
	printf("h=5\n");
	break;
case 7:
	printf("h=7\n");
	break;
default:
	printf("不到\n");
}

switch (h)
{

case 7:
	printf("h=7\n");
default:
	printf("不到\n");
}

int h1 = 4;
switch (h) {
case 6:
	switch (h1) {
	case 3:
		printf("h=6,h1=3\n");
	case 4:
		printf("h=6,h1=4\n");
	}
case 7:
	switch (h1) {
	case 3:
		printf("h=7,h1=3\n");
	case 4:
		printf("h=7,h1=4\n");
	}
default:
	printf("不到\n");
}

这部分内容较为简单,只要是格式问题,变量与赋值与括号要有空格,同时 花括号的位置需要注意。其次要留意break和default是可选的内容。break是退出判断。default是最后的进行项目,同时不需要判断。

当然此时也可以用

image.png

随后就是循环语句,与java类似,常见的循环语句有while循环 / for循环 / do...while循环 / 以及嵌套循环

	//循环简单测试

int i = 10;

while (i <= 13)
{
	printf("i=%d\n", i);
	i++;
}

printf("-=-=-=\n");

for (; i <= 16; i++)
{
	printf("i=%d\n", i);
}

printf("-=-=-=\n");

do
{
	printf("i=%d\n", i);
	i++;
} while (i <= 19);

image.png

循环和Java一样,大体跳过,需要注意的仍然是代码格式问题。与python类似,需要大量的空格以及分体式的排布。