本部分包含程序流程结构练习题:n的阶乘、1!+2!+3!+...+10!、二分查找、演示多个字符从两端移动,向中间汇聚、编写代码实现,模拟用户登录情节,而且只能登录三次、猜数字游戏。
笔记:
代码:
#define _CRT_SECURE_NO_WARNINGS 1
#include
#include
//1.1计算n的阶乘
int Mut01(int a1)
{
int sum = 1;
while (a1 > 0)
{
sum *= a1;
a1--;
}
return sum;
}
void menu()
{
printf("******************\n");
printf("******************\n");
printf("****1.开始游戏****\n");
printf("****0.退出游戏****\n");
printf("******************\n");
printf("******************\n");
printf("请选择:>");
}
void game()
{
int num = 0;
srand ((unsigned int)time(NULL));
int random = rand()%100+1;
printf("请输入:\n");
while (random != num)
{
scanf("%d", &num);
if (random
printf("猜大了哦\n");
}
else if (random > num)
{
printf("猜小了哦\n");
}
else if (random == num)
{
printf("猜对啦\n");
}
}
}
int main()
{
//程序流程结构训练题
//1.1计算n的阶乘
printf("请输入一个数,并得出它的阶乘:");
int a1 = 0;
scanf("%d",&a1);
int sum1=Mut01(a1);
printf("值为%d\n", sum1);
//1.2计算1!+2!+3!+...+10!
printf("计算1!+2!+3!+...+10!:");
int a2 = 10;
int sum2 = 0;
while (a2 > 0)
{
sum2 += Mut01(a2);
a2--;
}
printf("值为%d\n", sum2);
//1.3在一个有序数组中查找具体的某个数字n。(讲解二分查找)
int arr1[] = {1,2,3,4,5,6,7,8,9,10};
int length = sizeof(arr1) / sizeof(arr1[0]);
int a3 = 0;
int right = 0;
int left = length;
int mid = 0;
printf("请在一到十之间输入一个数,并找出它的下标");
scanf("%d", &a3);
while (right < left)
{
mid = (left+right) /2;
if (a3 > 10 || a3 < 0)
{
printf("没找到,请重输");
break;
}
if (a3 > arr1[mid])
{
right = mid;
}
else if (a3 < arr1[mid])
{
left = mid;
}
else if(a3==arr1[mid])
{
printf("找到了%d,下标为%d", arr1[mid], mid);
break;
}
}
//1.4演示多个字符从两端移动,向中间汇聚
char arr4[] = "welcome";
char arr41[] = "#######";
int right4 = strlen(arr4)-1;
int left4 = 0;
while(left4 <= right4)
{
arr41[left4] = arr4[left4];
arr41[right4] = arr4[right4];
printf("%s\n", arr41);
left4++;
right4--;
}
//1.5 编写代码实现,模拟用户登录情节,而且只能登录三次
char password[20] = { 0 };
printf("请输入密码:");
for (int i = 0;i < 3;i++)
{
scanf("%s", password);
if (strcmp(password, "123456")==0)
{
printf("登陆成功\n");
}
else
{
printf("登录失败\n");
}
if (i == 2)
{
printf("已输入三次,进入登录冷却\n");
}
}
//1.6 猜数字游戏
int input = 0;
do
{
menu();
scanf("%d", &input);
switch (input)
{
case 1:
printf("是猜数字游戏!\n");
game();
break;
case 0:
printf("成功退出");
break;
default:
printf("输入无效数字");
break;
}
} while (input);
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)