一、折半查找
题目:在数组{1.2.3.4.5.6.7.8.9.10}中找到7的位置
代码:
int main()
{
int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
int k = 7;
int left = 0;
int right = (sizeof(arr) / sizeof(arr[0])) - 1;
while (left <= right)
{ int mid = left + ((right - left) / 2);
if (arr[mid] > k)
{
right = mid - 1;
}
if (arr[mid] < k)
{
left = mid + 1;
}
if (arr[mid] == k)
{
printf("找到了下标是%d\n", mid);
break;
}
}
if (left > right)
{
printf("找不到\n");
}
return 0;
}
二、猜数字游戏
menu()
{
printf("****************************\n");
printf("***1.play**********2.exit***\n");
printf("****************************\n");
}
game()
{
int i = 0;
int b = rand()%100;
do
{
scanf_s("%d", &i);
if (i > b)
{
printf("大了\n");
}
if (i < b)
{
printf("小了\n");
}
if (i == b)
{
printf("输入正确\n");
}
} while (i != b);
}
int main()
{ srand((unsigned)time(NULL));
int a = 0;
do
{
menu();
scanf_s("%d", &a);
switch (a)
{
case 1:
printf("猜数字\n");
game();
break;
case 2:
printf("谢谢参与\n");
break;
default:
printf("输入错误,请重新输入>\n");
break;
}
} while (a==1||a!=2);
return 0;
}
三、关机程序
int main()
{
char arr[]="";
system("shutdown - s - t 60");
again:
printf("你的电脑还有一分钟就会关机\n");
printf("请输入:我是猪,解除关机\n");
scanf("%s", arr);
if (strcmp(arr, "我是猪") == 0)
{
system("shutdown -a");
}
else
{
goto again;
}
return 0;
}