文章目录
- goto语句
- 猜数字小游戏
文章内容
1.goto语句
C语言中提供了可以随意滥用的 goto语句和标记跳转的标号。从理论上 goto语句是没有必要的,实践中没有goto语句也可以很容易的写出代码。但是某些场合下goto语句还是用得着的,最常见的用法就是终止程序在某些深度嵌套的结构的处理过程。
例如:一次跳出两层或多层循环。
多层循环这种情况使用break是达不到目的的。它只能从最内层循环退出到上一层的循环。goto语言真正适合的场景如下:
for(...)
for(...)
{
for(...)
{
if(disaster)
goto error;
}
}
…
error:
if(disaster)
// 处理错误情况
//int main()
//{
//again:
// printf("hehe\n");
// printf("hehe\n");
// printf("hehe\n");
// printf("hehe\n");
//
// goto again;
//
//end:
// return 0;
//}
goto 语句只能一个函数内部跳转,不能跨函数跳转的。
2.猜数字小游戏
#include <stdio.h>
#include<stdlib.h>
#include<time.h>
//void menu()
//{
// printf("############################\n");
// printf("####1. play 0.exit ####\n");
// printf("############################\n");
//}
//
//void game()
//{
// RAND_MAX;
// int ret = rand()%100+1; //为了使游戏变得简单,我们将随机数的值设置在1~100之间
// //printf("%d\n",ret);
// int guess= 0;
//
// while (1)
// {
// printf("开始猜数字游戏:>");
// scanf("%d", &guess);
// if (guess == ret)
// {
// printf("猜对了:>\n");
// break;
// }
// if (guess < ret)
// {
// printf("猜小了:>\n");
// }
// if(guess > ret)
// {
// printf("猜大了\n");
// }
// }
//}
//
//
//int main()
//{
// int input = 0;
// srand((unsigned int)(time(NULL))); // 使用rand函数之前我们要先使用srand(这是定义)
// 但是我们要先给srand一个随机值,这个随机值我们选用time函数
// 我们将time()转换为unsigned int 类型这样srand才能接收,
// 但是我们这个函数在程序中只使用依次就行了,所以把这个函数放到了主函数里,
// 如果放到game函数里的话会使srand随机值每次都发生变化
// do // 为起到能够多次循环的效果我们选用do while 循环
// {
// menu(); //此处打印游戏的菜单
// printf("请选择:>");
// scanf("%d", &input);
// switch (input) //此处用switch语句进行选择
// {
// case 1:
// game(); //此处我们调用game函数进行实现游戏的功能,
// break;
// case 0:
// printf("退出游戏:>");
// break;
// default:
// printf("选择错误:>");
// break;
//
// }
// } while (input); //将每次出来input的值进行判断若为零将不进入循环。
//
// return 0;
//}