day 10_15

1.完成猜数字游戏。

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void menu();
void game();
int main()
{
	int input;
	srand(time(NULL));
	do
	{
		menu();
		printf("input your choice:");
		scanf("%d", &input);
		switch (input)
		{
		case 1:
			game();
			break;
		case 2:
			break;
		default:
			printf("error input,please input again\n");
			break;
		}
	} while (input);
	system("pause");
}
void menu()
{
	printf("****************\n");
	printf("*** 1 play *****\n");
	printf("*** 2 exit *****\n");
	printf("****************\n");
}
void game()
{
	int random_num = rand() % 100 + 1;
	int input = 0;
	while (1)
	{
		printf("请输入猜的数字:");
		scanf("%d", &input);
		if(input > random_num)
		{
			printf("猜大了\n");
		}
		else if(input < random_num)
		{
			printf("猜小了\n");
		}
		else
		{
			printf("猜对了\n");
			break;
		}
	}
}

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

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int bin_search(int arr[], int left, int right, int key);
int main()
{
	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 key = 5;
	int result;
	result = bin_search(arr, 0, right, key);
	printf("%d\n", result);
	system("pause");
}
int bin_search(int arr[], int left, int right,int key)
{
	int middle = 0;
	while (left <= right)
	{
		middle = (left + right) / 2;
		if (arr[middle] > key)
		{
			right = middle - 1;
		}
		else if (arr[middle] < key)
		{
			left = middle + 1;
		}
		else
		{
			return middle;   //找到了
		}
	}
	return -1;    //没找到

}

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

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
	char arr[10] = "";
	int count = 0;
	for (count = 0; count < 3; ++count)
	{
		printf("please input:\n");
		scanf("%s", arr);
		if (strcmp(arr, "password") == 0)
			break;
	}
	if (count == 3)
	{
		printf("exit\n");
	}
	else
	{
		printf("log in\n");
	}
	system("pause");
}

4.编写一个程序,可以一直接收键盘字符,
如果是小写字符就输出对应的大写字符,
如果接收的是大写字符,就输出对应的小写字符,
如果是数字不输出。

#include<stdio.h>
#include<stdlib.h>
int main()
{
	int ch;
	printf("请输入一个字符:\n");
	while ((ch = getchar()) != EOF)
	{
		if (ch >= 'a'&&ch <= 'z')
			printf("%c\n", ch - 32);
		else
		if (ch >= 'A'&&ch <= 'Z')
			printf("%c\n", ch + 32);
		else
		if (ch >= '0'&&ch <= '9')
			;
		else
			;
	}
	printf("\n");
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/busybox1587/article/details/83062393