#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int menu() {
printf("===============\n");
printf("1.开始游戏\n");
printf("0.结束游戏\n");
printf("===============\n");
}
void Game() {
int tuGuess = rand() % 100 + 1;
int num = 0;
while (1) {
printf("请输入猜的数字(0~100)\n");
scanf("%d", &num);
if (num < tuGuess) {
printf("低了!\n");
}
else if (num > tuGuess) {
printf("高了!\n");
}
else {
printf("猜对了!游戏结束!\n");
break;
}
}
}
int main() {
int choice = 0;
int t = time(0);
printf("t = %d\n",t);
srand(t);
while (1) {
int choice = menu();
printf("请输入你的选择\n");
scanf("%d", &choice);
if (choice == 1) {
Game();
}
else if (choice == 0) {
printf("goodbey!\n");
break;
}
else {
printf("输入错误,请重新输入\n");
}
}
system("pause");
return 0;
}
2 写代码可以在整型有序数组中查找想要的数字,找到了返回下标,找不到返回-1.(折半查找)
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
int main() {
int a;
printf("请输入一个整数,看其是否存在在已知数组中(存在输出下标,不存在输出-1):");
scanf("%d", &a);
int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
int left = 0;
int right = sizeof(arr) / sizeof(arr[0]) - 1;
int b = 0;
while (left <= right) {
b = (left + right) / 2;
if (arr[b] > a) {
right = b - 1;
}
else if (arr[b] < a) {
left = b + 1;
}
else
break;
}
if (left <= right) {
printf("%d\n", b);
}
else {
printf("-1\n");
}
system("pause");
return 0;
}