1.完成猜数字游戏
#include<stdio.h>
#include<stdlib.h>
#include <time.h>
int main()
{
int i = 0, j = 0;
int p;
srand(time(NULL));
p = rand() % 100 + 1;
printf("请输入一个数字\n");
for (int a = 0;; a++)
{
scanf_s("%d", &i);
if (i == p)
break;
else if (i > p)
printf("高了\n");
else
printf("低了\n");
}
printf("猜对了\n");
system("pause");
}
2.写代码可以在整型有序数组中查找想要的数字,
找到了返回下标,找不到返回-1.(折半查找)
#include<stdio.h>
#include<stdlib.h>
int main()
{
double arr[9] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int want = 0;
int left = 0;
int right = 9;
int i = 0;
printf("请输入数字\n");
scanf_s("%d", &want);
while (left <= right)
{
i = (left + right) / 2;
if (want < arr[i])
{
right = i - 1;
}
else if (want > arr[i])
{
left = i + 1;
}
else
break;
}
if (left <= right)
{
printf("%d\n", i);
}
else
{
printf("-1");
}
system("pause");
}
}
3.编写代码模拟三次密码输入的场景。
最多能输入三次密码,密码正确,提示“登录成功”,密码错误,
可以重新输入,最多输入三次。三次均错,则提示退出程序
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int i = 0;
char str1[1024] = { 0 };
for (i = 0; i < 3; i++)
{
printf("请输入6位密码\n");
scanf_s("%s", &str1);
if (strcmp(str1,"123456") == 0)
{
printf("登录成功\n");
break;
}
}
if (i == 3)
printf("退出程序");
system("pause");
}
4.编写一个程序,可以一直接收键盘字符,
如果是小写字符就输出对应的大写字符,
如果接收的是大写字符,就输出对应的小写字符,
如果是数字不输出。
#include<stdio.h>
#include<stdlib.h>
int main()
{
int ch;
printf("请输入一个字符:\n");
while((ch=getchar())!=EOF)
{
if(ch>='a'&&ch<='z')
{
ch=ch-32;
printf("%c\n",ch);
}
else if(ch>='A'&&ch<='Z')
{
printf("%c\n",ch+32);
ch=ch+32;
}
else
if(ch>='0'&&ch<='9')
;
else
;
}
printf("\n");
system("pause");
}