//不限制次数的猜数字游戏
源代码如下:
#define _CRT_SECURE_NO_WARNINGS 1 #include<stdio.h> #include<stdlib.h>
void menu() { printf("*****************n"); printf("** 1. play ******n"); printf("** 0. exit ******n"); printf("*****************n"); } //void表示函数不返回任何值 void game() { int r = rand() % 100 1; int guess = 0; while (1) { printf("请猜数字:"); scanf("%d", &guess); if (guess > r) { printf("猜大了n"); } else if (guess < r) { printf("猜小了n"); } else { printf("恭喜你,答对了n"); break; } } } int main() { int input = 0; srand((unsigned int)time(NULL)); do { //打印菜单 menu(); //请选择 printf("请选择:"); scanf("%d", &input); switch (input) { case 1: game(); printf("猜数字n"); break; case 0: printf("退出游戏n"); break; default: printf("选择错误,重新选择n"); break; } } while (input); return 0; }
下面这个是有限制次数的猜数字游戏
//源代码如下:
void menu() { printf("*****************n"); printf("** 1. play ******n"); printf("** 0. exit ******n"); printf("*****************n"); } //void表示函数不返回任何值 void game() { int r = rand() % 100 1; int guess = 0; int count = 5; while (count) { printf("请猜数字:"); scanf("%d", &guess); if (guess > r) { printf("猜大了n"); } else if (guess < r) { printf("猜小了n"); } else { printf("恭喜你,答对了n"); break; } count--; } if (count == 0) { printf("用完了所有的机会,猜数字失败,正确的值是%dn",r); } } int main() { int input = 0; srand((unsigned int)time(NULL)); do { //打印菜单 menu(); //请选择 printf("请选择:"); scanf("%d", &input); switch (input) { case 1: game(); printf("猜数字n"); break; case 0: printf("退出游戏n"); break; default: printf("选择错误,重新选择n"); break; } } while (input); return 0; }
今天的博客就到这了,下期再见。