程序员养成记(第七天)

//猜数字游戏
#define _CRT_SECURE_NO_WARNINGS
#include
#include
#include
#include
void menu()
{
printf(“");
printf(“1.play******”);
printf(“2.exit***”);
printf("
”);
}
void game()
{
int to_guess = rand() % 100 + 1;//求100之内的数
int num = 0;
while (1)
{
printf(“请输入一个1-100的整数>:”);
scanf("%d", &num);
if (num > to_guess)
{
printf(“猜大了\n”);
}
else if (num < to_guess)
{
printf(“猜小了\n”);
}
else
{
printf(“猜对了\n”);
break;
}
}
}
int main()
{
srand((unsigned)time(0));
int input = 0;
do{
menu();
printf(“请选择>:”);
scanf("%d", &input);
switch(input)
{
case 1:
game();
break;
case 0:
break;
default:
printf(“您的输入有误\n”);
break;
}
}
while (input);
return 0;
}
//二分法查找
#define _CRT_SECURE_NO_WARNINGS
#include
#include
#include
#include
int binarysearch(int arr[], int left, int right, int key){
while (left <= right){
int mid = left + (right - left) / 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[6] = { 1, 2, 3, 4, 5, 6 };
int len = sizeof(arr) / sizeof(arr[0]);
int index= binarysearch(arr, 0, (len - 1), 4);
printf("%d\n",index);
system(“pause”);
return 0;
}

你可能感兴趣的:(程序员养成记(第七天))