猜数字小游戏:
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
/*
猜数字小游戏
*/
int menu() {
printf(“1.开始游戏\n”);
printf(“0.结束游戏\n”);
printf("\n\n");
int choice = 0;
printf(“请选择菜单:”);
while (1) {
scanf("%d", &choice);
if (choice == 1) {
return 1;
} else if (choice == 0) {
printf(“游戏结束\n”);
return 0;
} else {
printf(“输入有误,请重新输入\n”);
}
}
}
void game() {
srand((unsigned int)time(0));
int num = rand() % 100 + 1;
printf(“请输入你所猜的数字(1 - 100)\n”);
while (1) {
int guess = 0;
scanf("%d", &guess);
if (guess > num) {
printf(“高了\n”);
} else if (guess < num) {
printf(“低了\n”);
} else {
printf(“恭喜你,猜对了\n”);
break;
}
}
}
int main() {
while (menu() == 1) {
game();
}
return 0;
}
折半查找法(二分法):
#include<stdio.h>
/*
用折半查找发查找想要的数字
*/
int main() {
int a[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
int left = 0;
int right = sizeof(a) / sizeof(a[0]);
printf("请输入你要找的数字:\n");
int num = 0;
scanf("%d", &num);
while (left <= right) {
int temp = (left + right) / 2;
if (num > a[temp]) {
left = temp + 1;
} else if (num < a[temp]) {
right = temp - 1;
} else {
printf("找到了,在 %d 的位置\n", temp);
break;
}
}
if (left > right) {
printf("没找到\n");
}
return 0;
}
三次密码输入:
#include<stdio.h>
#include<string.h>
/*
输入密码,最多给3次机会
*/
int main() {
char password[1024] = { 0 };
printf("请输入你的密码: \n");
int i = 0;
for ( ; i < 3; i++) {
scanf("%s", &password);
if (strcmp(password, "1234aa..") == 0) {
printf("密码正确,登陆成功\n");
break;
}
printf("密码错误,请重新输入\n");
}
if (i == 3) {
printf("登陆失败\n");
}
return 0;
}
字母大小写转换:
(数字及其他字符不能转换)
#include<stdio.h>
/*
字母的大小写转换
*/
int menu() {
printf("**********1. 转换 **********\n");
printf(“0.结束转换\n”);
int choice = 0;
while (1) {
scanf("%d", &choice);
if (choice == 1) {
return 1;
} else if (choice == 0) {
return 0;
} else {
printf(“输入有误,请重新输入\n”);
}
}
}
void exchange() {
printf(“请输入你要转换大小写的字母\n”);
char c;
while ((c = getchar()) != ‘\n’);
c = getchar();
if (c >= ‘a’ && c <= ‘z’) {
printf("%c\n", c - 32);
} else if (c >= ‘A’ && c <= ‘Z’) {
printf("%c\n", c + 32);
} else {
printf("不存在大小写转换\n");
}
while ((c = getchar()) != '\n');
}
int main() {
char c = 0;
while (menu() == 1) {
exchange();
}
return 0;
}