1.完成猜数字游戏。
2.完成折半查找代码的编写和探索。
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void menu() //猜数字游戏
{
printf("*******************************\n");
printf("******* 1.play 0.exit ******\n");
printf("*******************************\n");
}
enum OP
{
EXIT,
PLAY
};
int main()
{
int input = 0;
srand((unsigned)time(NULL));
do
{
menu();
printf("请选择>:");
scanf("%d", &input);
switch (input)
{
case PLAY:
{
int num = rand() % 100;
int num2 = 0;
while (1)
{
printf("请猜一个1~100之间的数字:>");
scanf("%d", &num2);
if (num2 > num)
{
printf("错误,猜大了\n");
}
else if (num2 < num)
{
printf("错误,猜小了\n");
}
else
{
printf("恭喜你,猜对了\n");
break;
}
}
}
break;
case EXIT:
break;
default:
printf("选择错误!\n");
break;
}
} while (input);
return 0;
}
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
//二分查找
int bin_search(int arr[], int key, int left, int right)
{
while (left <= right)
{
int mid = (left + right) / 2;
if (arr[mid]>key)
{
right = mid - 1;
}
else if (arr[mid]<key)
{
left = mid + 1;
}
else
{
return mid;
}
}
return -1;
}
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6, 8, 9, 10, 11 };
int sz = sizeof(arr) / sizeof(arr[0]);
int ret = bin_search(arr, 10, 1, 11);
if (ret == -1)
printf("找不到\n");
else
printf("所查找数在数组arr中下标为:%d\n", ret);
return 0;
}