C语言练手小代码------five

1 猜数字游戏
功能:可以随机猜一个数字,直到猜对为止,虽然游戏有些无聊,但是可以锻炼我们使用二分查找的思想来快速查找数字。代码已经托管到码云上,点击打开链接。下边附上一张大概的游戏截图:

2.写代码可以在整型有序数组中查找想要的数字,找到了返回下标,找不到返回-1.(折半查找)
 
 
#define _CRT_SECURE_NO_WARNINGS ch
#include<stdio.h>
#include<Windows.h>
#include<math.h>
#include<time.h>
//写代码可以在整型有序数组中查找想要的数字,找到了返回下标,找不到返回 - 1.(折半查找)
int binary_search(int arr[],int sz,int key){
	int left = 0;
	int right = sz - 1;
	int mid = 0;
	while (left<=right){
		mid = left + (right - left)/2;
		if (key > arr[mid]){
			left = mid + 1;
		}
		else if (key < arr[mid]){
			right = mid - 1;
		}
		else{
			return mid ;
		}
	}
	return -1;
}
int main(){
	int arr[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
	int sz = 0;
	sz = sizeof(arr) / sizeof(arr[0]);
	int key = -1;
	int ret=binary_search(arr, sz,key);
	if (ret == -1){
		printf("未找到!\n");
	}
	else{
		printf("下标为:%d\n", ret);
	}
	system("pause");
	return 0;
}

运行结果:(两种测试用例)
找到了:
当key为3时:

没找到:当key为-1时

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

#define _CRT_SECURE_NO_WARNINGS ch
#include<stdio.h>
#include<Windows.h>
#include<math.h>
#include<time.h>
//编写代码模拟三次密码输入的场景。
//最多能输入三次密码,密码正确,提示“登录成功”, 密码错误,可以重新输入,最多输入三次。
//三次均错,则提示退出程序。
int main(){
	char arr[10] = { 0 };
	int count = 3;
	while (count--){
		printf("请输入密码:");
		scanf("%s", arr);
		if (0 == strcmp(arr, "123456")){
			printf("密码正确!登陆成功\n");
		}
		else{
			printf("您还有%d次机会\n", count);
		}
	}
	system("pause");

	return 0;
}

实验结果:

4.编写一个程序,可以一直接收键盘字符,如果是小写字符就输出对应的大写字符,如果接收的是大写字符,就输出对应的小写字符,如果是数字不输出。
#define _CRT_SECURE_NO_WARNINGS ch
#include<stdio.h>
#include<Windows.h>
#include<math.h>
#include<time.h>
//编写一个程序,可以一直接收键盘字符,如果是小写字符就输出对应的大写字符,
//如果接收的是大写字符,就输出对应的小写字符,如果是数字不输出。
int main(){
	int ch=0;
	while (ch != EOF){
		scanf("%c", &ch);
		if (ch >= 'a'&&ch <= 'z'){
			printf("%c", ch - 32);
		}
		if (ch >= 'A'&&ch <= 'Z'){
			printf("%c", ch + 32);
		}
	}
	system("pause");
	return 0;
}

实验结果:

猜你喜欢

转载自blog.csdn.net/superwangxinrui/article/details/79956163