1.有序数组中折半查找想要的数字 2.猜数字游戏 3.模拟三次密码输入的场景

1.写代码可以在整型有序数组中查找想要的数字, 找到了返回下标,找不到返回-1.(折半查找)

#include<stdio.h>
#include<windows.h>
int binarysearch(int arr[], int key, int left, int right)
{
	while (left <= right)
	{
		int mid = (left + right) >> 1;
		if (arr[mid] > key)
		{
			right = mid - 1;
		}
		else if (arr[mid] == key)
		{
			return mid;
		}
		else
		{
			left = mid + 1;
		}
	}
	return -1;
}
int main()
{
	int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
	int len = sizeof(arr) / sizeof(arr[0]);
	int left = 0;
	int right = len - 1;
	int index = binarysearch(arr,8, left, right);
	printf("%d", index);
	system("pause");
	return 0;
}

2.猜数字游戏

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<Windows.h>
#include<time.h>
void play()
{
	srand((unsigned long)time(NULL));
	int random = rand() % 200 + 1;
	int data = 0;
	while (1)
	{
		printf("Input Data:\n");
		scanf("%d", &data);
		if (data > random){
			printf("猜大了!\n");
		}
		else if (data < random){
			printf("猜小了!\n");
		}
		else
		{
			printf("恭喜你猜对了!\n");
			break;
		}
	}
}
int game()
{
	while (1)
	{
		int select = 0;
		printf("1.play\n");
		printf("2.exit\n");
		printf("请选择:\n");
		scanf("%d", &select);
		switch (select)
		{
		case 1:play();
			break;
		case 2:printf("Good Bye!\n");
			return 0;
		default:
			printf("Input Error,Please Try Again !\n");
			break;
		}
	}
}
int main()
{
	game();
	system("pause");
	return 0;
}

3.编写代码模拟三次密码输入的场景。 最多能输入三次密码,密码正确,提示“登录成功”,密码错误, 可以重新输入,最多输入三次。三次均错,则提示退出程序。

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
#include<Windows.h>
const char Name[] = "limeng";
const char Password[] = "123456";
void Login()
{
	int count = 3;
	while (count > 0){
		char name[32], password[32];
		printf("Input Your Login Name:");
		scanf("%s", &name);
		printf("Input Your Password:");
		scanf("%s", &password);
		if (strcmp(name, Name) == 0 && strcmp(password, Password) == 0)
		{
			printf("login success!");
			break;
		}
		else{
			printf("Input Error!\n");
			count--;
			printf("You Have %d times!\n", count);
		}
	}
}
int main()
{
	Login();
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_44930562/article/details/90321028