c语言实例(5)

1 猜数字游戏

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int menu() {
	printf("===============\n");
	printf("1.开始游戏\n");
	printf("0.结束游戏\n");
	printf("===============\n");

}

void Game() {
	int tuGuess = rand() % 100 + 1;
	int num = 0;
	while (1) {
		printf("请输入猜的数字(0~100)\n");
		scanf("%d", &num);
		if (num < tuGuess) {
			printf("低了!\n");
		}
		else if (num > tuGuess) {
			printf("高了!\n");
		}
		else {
			printf("猜对了!游戏结束!\n");
			break;
		}
	}
}

int main() {
	int choice = 0;
	int t = time(0);
	printf("t = %d\n",t);
	srand(t);
	while (1) {
		int choice = menu();
		printf("请输入你的选择\n");
		scanf("%d", &choice);
		if (choice == 1) {
			Game();
		}
		else if (choice == 0) {
			printf("goodbey!\n");
			break;
		}
		else {
			printf("输入错误,请重新输入\n");
		}
		
	}
	system("pause");
	return 0;
}

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

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
int main() {
	int a;
	printf("请输入一个整数,看其是否存在在已知数组中(存在输出下标,不存在输出-1):");
	scanf("%d", &a);
	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 b = 0;
	while (left <= right) {
		b = (left + right) / 2;
		if (arr[b] > a) {
			right = b - 1;
		}
		else if (arr[b] < a) {
			left = b + 1;
		}
		else
			break;
	}
	if (left <= right) {
		printf("%d\n", b);
	}
	else {
		printf("-1\n");
	}
	system("pause");
	return 0;
}

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值