//完成猜数字游戏
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include <stdlib.h>
#include <time.h>
void menu()
{
printf("*************************\n");
printf("***** 1. play *****\n");
printf("***** 0. exit *****\n");
printf("*************************\n");
}
void game()
{
int x = 0;
int num = 0;
x = rand()%100;
while(1)
{
printf("请猜数字\n");
scanf("%d", &num);
if(x < num)
printf("猜大了\n");
else if(x > num)
printf("猜小了\n");
else if(x == num)
{ printf("猜对了\n");
break;
}
}
}
int main()
{
int n = 0;
srand((unsigned int)time(NULL));
do
{
menu() ;
printf("请选择\n");
scanf("%d", &n);
switch(n)
{
case 1:
game();
break;
case 0:
printf("退出游戏\n");
break;
default:
printf("选择错误\n");
break;
}
}while(n);
return 0;
}
//折半查找法
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include <stdlib.h>
int binary_search(int arr[], int s, int left, int right)
{
int mid = 0;
while(left<=right)
{
mid = left+(right-left)/2;
if(s > arr[mid])
left = mid+1;
else if(s < arr[mid])
right = mid+1;
else if(s == arr[mid])
return mid;
}
return -1;
}
int main()
{
int arr[] = {1,2,3,4,5,6,7,8,9,10};
int s = 0;
int n = 0;
printf("请输入需要查找的数字\n");
scanf("%d", &s);
n = binary_search( arr, s, 0, 9);
if(n==-1)
printf("找不到\n");
else
printf("找到了 %d", n);
return 0;
}
//模拟三次密码输入的场景
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
int main()
{
int i = 0;
char password[10] = {0};
for(i=0; i<3; i++)
{
printf("请输入密码\n");
scanf("%s", password);
if( strcmp("abc123", password) == 0)
{
printf("登陆成功\n");
return 0;
}
else
printf("密码错误\n");
}
if(3 == i)printf("三次密码输入错误,退出程序\n");
return 0;
}
//输入一段字符,数字不输出,字符大小写转换
#include<stdio.h>
int main()
{
int ch = 0;
while((ch=getchar()) != EOF)
{
if(ch <= '9' && ch >= '0' )
printf(" ");
if(ch <= 'z' && ch >= 'a')
printf("%c ", ch-32);
if(ch <= 'Z' && ch >= 'A')
printf("%c ", ch+32);
}
return 0;
}