1.完成猜数字游戏。
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void cszyx();
int main()
{
int input = 0;
do{//改良为目录函数。可选择猜数范围。
printf("*****************\n");
printf("*****请选择:*****\n");
printf("***1.开始游戏****\n");
printf("***0.退出游戏****\n");
printf("*****************\n");
scanf("%d", &input);
switch (input)
{
case 1:cszyx(); break;
case 0:break;
default: printf("选择错误,请重新输入数字:\n");
break;
}
} while (input);
system("pause");
return 0;
}
void cszyx()
{
int num = 0, s = 0;
printf("请输入你猜的数:\n");
srand((unsigned int)time(NULL));//“起点”,产生随机种子seedrand。
num = rand()%4;//根据种子生成随机数。
while (1)//改良为猜10次可选择不玩游戏了。
{
scanf("%d", &s);
if (s > num) { printf("猜大啦!\n"); continue; }
if (s < num){ printf("猜小啦!\n"); continue; }
if (s == num) { printf("恭喜你,猜对啦!\n"); break; }
}
运行结果为:
2.写代码可以在整型有序数组中查找想要的数字,
找到了返回下标,找不到返回-1.(折半查找)
2.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int main()
{ int a[14]={22,33,43,3,2,1,4,5,6,7,4,32,35,6};
int left=0,mid,right,z;
printf("请输入要找的数:\n");
scanf("%d", &z);
right = sizeof(a) / sizeof(a[0]) - 1;
while (left <= right)
{
mid = left + (right -left ) / 2;
if (a[mid]< z) left = mid + 1;
else if (a[mid]>z) right = mid - 1;
else break;
}
if (left <= right) printf("找到啦!下标是%d", mid);
if(left>right) printf("-1");
system("pause");
return 0;
}
3.编写代码模拟三次密码输入的场景。
最多能输入三次密码,密码正确,提示“登录成功”,密码错误,
可以重新输入,最多输入三次。三次均错,则提示退出程序。
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int i = 0;
char a[10] = {"aaa"};
char b[10];
for (i = 0; i < 3; i++)
{
printf("请输入密码\n");
scanf("%s",b);
if (strcmp(a, b) == 0) { printf("密码正确!\n"); break; }
else if (i < 2) printf("密码错误!请重新输入\n");
if (i == 2) printf("错误三次,即将退出系统");
}
system("pause");
return 0;
}
4.编写一个程序,可以一直接收键盘字符,
如果是小写字符就输出对应的大写字符,
如果接收的是大写字符,就输出对应的小写字符,
如果是数字不输出。
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int ch1, ch2;
//***getchar返回的是int型的,定义成char型也可以,因为char和int可以互相转化***
while ((ch1 = getchar())!= EOF)/**/需要这样才可以不断输入,得到一个字符串,如果不这样写,只是ch1=getchar,只能得到一个字符。**
{
if (ch1 <= 'Z'&&ch1 >= 'A'){ ch2 = ch1 + 32; putchar(ch2); }
if (ch1 <= 'z'&&ch1 >= 'a'){ ch2 = ch1 - 32; putchar(ch2); }
}
system("pause");
return 0;
}
运行结果为