1.折半查找
#include<stdio.h>
int main()
{
int arr[] = {0,1,2,3,4,5,6,7,8,9};
int arr[] = {0,1,2,3,4,5,6,7,8,9};
int l=0;
int r=9;
int key= 8;
int mid = 0;
while(l<=r)
{
mid = l+(r-l)/2;
if(arr[mid]<key)
{
l = mid+1;
}
else if(arr[mid]>key)
{
r = mid-1;
}
else
{
printf("%d\n",mid);
while(l<=r)
{
mid = l+(r-l)/2;
if(arr[mid]<key)
{
l = mid+1;
}
else if(arr[mid]>key)
{
r = mid-1;
}
else
{
printf("%d\n",mid);
break;
}
}
return 0;
}
}
}
return 0;
}
2.模拟三次密码输入
#include<stdio.h>
#include<string.h>
int main()
{
char arr[10] = {0};
int i = 0;
for(i=0; i<3; i++)
{
printf("请输入密码");
scanf("%s", arr);
if(0 == strcmp(arr,"666666"))
{
break;
}
else
{
printf("密码错误\n");
}
}
if(3 == i)
printf("错误三次,登录失败\n");
else
printf("恭喜登录成功\n");
return 0;
}
{
char arr[10] = {0};
int i = 0;
for(i=0; i<3; i++)
{
printf("请输入密码");
scanf("%s", arr);
if(0 == strcmp(arr,"666666"))
{
break;
}
else
{
printf("密码错误\n");
}
}
if(3 == i)
printf("错误三次,登录失败\n");
else
printf("恭喜登录成功\n");
return 0;
}
3.编写一个程序,可以一直接收键盘字符,如果是小写字符就输出对应的大写字符,如果接收的是大写字符,就输出对应的小写字符,如果是数字不输出
int include<stdio.h>
int main()
{
int ch = 0;
while((ch=getchar()) != EOF)
{
if(ch>='A' && ch<='Z')
{
printf("%c",ch+32);
}
else if(ch >= 'a' && ch<='z')
{
printf("%c ", ch-32);
}
{
int ch = 0;
while((ch=getchar()) != EOF)
{
if(ch>='A' && ch<='Z')
{
printf("%c",ch+32);
}
else if(ch >= 'a' && ch<='z')
{
printf("%c ", ch-32);
}
}
return 0;
}
return 0;
}
4.猜数字游戏
#include<stdio.h>
#indlucde<stdlib.h>
void menu()
{
printf("1.play 0.exit\n");
}
{
printf("1.play 0.exit\n");
}
void game()
{
int num = 0;
int input = 0;
num = rand()%100+1;
while(1)
{
printf("请猜一个数字");
scanf("%d", &input);
if(input > num)
{
printf("大了\n");
}
else if(input < num)
{
printf("小了\n");
}
else
{
printf("Good game!\n");
break;
}
}
}
int main()
{
int input = 0;
srand((unsigned int)time(NULL));
do
{
menu();
scanf("%d", &input);
switch(input)
{
case 1:
game();
break;
case 0:
printf("退出游戏\n");
break;
default:
printf("选择错误\n");
break;
}
} while (input);
return 0;
}
{
int num = 0;
int input = 0;
num = rand()%100+1;
while(1)
{
printf("请猜一个数字");
scanf("%d", &input);
if(input > num)
{
printf("大了\n");
}
else if(input < num)
{
printf("小了\n");
}
else
{
printf("Good game!\n");
break;
}
}
}
int main()
{
int input = 0;
srand((unsigned int)time(NULL));
do
{
menu();
scanf("%d", &input);
switch(input)
{
case 1:
game();
break;
case 0:
printf("退出游戏\n");
break;
default:
printf("选择错误\n");
break;
}
} while (input);
return 0;
}