猜数字游戏
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
void menu()
{
printf("*************************\n");
printf("****** 1.玩游戏 ********\n");
printf("****** 0.退出 ********\n");
printf("*************************\n");
}
void game()
{
int num = rand() % 100 + 1;
int n = 0;
while (1)
{
printf("请猜数字:>");
scanf("%d", &n);
if (n > num)
{
printf("猜大了\n");
}
else if (n < num)
{
printf("猜小了\n");
}
else
{
printf("恭喜你,猜正确了\n");
break;
}
}
}
int main()
{
srand((unsigned int)time(NULL));
int choice = 0;
do{
menu();
printf("请输入你的选择:>");
scanf("%d", &choice);
switch (choice)
{
case 1:
game();
break;
case 0:
printf("您已成功退出了游戏\n");
break;
default:
printf("输入错误\n");
break;
}
} while (choice);
}
折半查找
在整型有序数组中查找想要的数字,找到了返回下标,找不到返回-1.
二分查找数组必须有序
#include<stdio.h>
#include<stdlib.h>
int BinarySearch(int arr[], int sz,int key)
{
int left = 0;
int right = sz - 1;
while (left <= right)
{
int mid = (left + right) / 2;
if (arr[mid] > key)
{
right = mid - 1;
}
else if (arr[mid] < key)
{
left = mid + 1;
}
else
{
return mid;
}
}
return -1;
}
int main()
{
int arr[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sz = sizeof(arr) / sizeof(arr[0]);
int key = 12;
int ret=BinarySearch(arr, sz, key);
printf("%d\n", ret);
system("pause");
return 0;
}
编写一个程序,可以一直接收键盘字符,如果是小写字符就输出对应的大写字符,如果接收的是大写字符,就输出对应的小写字符,如果是数字不输出
#include<stdio.h>
#include<stdlib.h>
int main()
{
char ch = 0;
while ((ch = getchar()) != EOF)
{
if ((ch > 'A') && (ch < 'Z'))
putchar(ch + 32);
else if ((ch>'a') && (ch < 'z'))
putchar(ch - 32);
}
system("pause");
return 0;
}