一些简单的练习题
1.计算n的阶乘
#include <stdio.h>
int main()
{
int i = 1;
int sum = 1;
int n = 0;
scanf("%d", &n);
for (i = 1; i <= n; i++)
{
sum *= i;
}
printf("%d\n", sum);
return 0;
}
下面用递归
#include <stdio.h>
int Factorial(int x)
{
if (x <= 1)
return 1;
else
return x * Factorial(x - 1);
}
int main()
{
int n = 0;
scanf("%d", &n);
printf("%d\n", Factorial(n));
return 0;
}
2.计算1!+2!+3!+…+ 10!
#include <stdio.h>
int main()
{
int i = 1;
int sum = 0;
int n = 0;
int ret = 1;
scanf("%d", &n);
for (i = 1; i <= n; i++)
{
ret *= i;
sum += ret;
}
printf("%d\n", sum);
return 0;
}
3.在数组中查找某个数
#include <stdio.h>
int main()
{
int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
int sz = sizeof(arr) / sizeof(arr[0]);
int left = 0; //数组的起始位置
int right = sz - 1; //数组的末尾位置
int mid;
int k = 0; //要查找的数字
scanf("%d", &k);
while (left <= right)
{
mid = left + (right - left) / 2;
if (arr[mid] > k)
{
right = mid - 1;
}
else if (arr[mid] < k)
{
left = mid + 1;
}
else
{
printf("找到了,下标为%d\n", mid);
break;
}
}
if (left > right)
printf("没找到\n");
return 0;
}
二分查找
4.演示多个字符从两端移动,向中间汇聚
#include <stdio.h>
#include <windows.h>
int main()
{
char arr1[] = "###################";
char arr2[] = "hello world!!!!!!!!";
int left = 0;
int right = strlen(arr1) - 1;
while (left <= right)
{
arr2[left] = arr1[left];
arr2[right] = arr1[right];
printf("%s\n", arr2);
left++;
right--;
Sleep(1000); //在屏幕上显示1s,单位为ms
system("cls"); //清空屏幕
}
printf("%s\n", arr2);
return 0;
}
模拟用户登录情景,只能登录三次
#include <stdio.h>
#include <string.h>
int main()
{
char passw[20]="password"; //原来的密码
char pa[20]; //要输入的密码
int i;
for (i = 1; i <= 3; i++)
{
printf("请输入密码:");
scanf("%s", pa);
if (strcmp(pa, passw) == 0) //strcmp函数:判断两个字符串是否相等
break;
else
printf("密码错误,请重新输入\n");
}
if (i > 3)
{
printf("exit\n");
}
else
printf("login in\n");
return 0;
}
猜数字游戏
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
void menu()
{
printf("************************\n");
printf("****1.play 0.exit****\n");
printf("************************\n");
//printf("************************\n");
}
void game(int RandNum)
{
int n;
while (1)
{
printf("请猜数字(0~99):>");
scanf("%d", &n);
if (n > 0 && n < 99)
{
if (RandNum > n)
printf("猜小了\n");
else if (RandNum < n)
printf("猜大了\n");
else
{
printf("恭喜你!\n");
break;
}
}
else
printf("请输入0到99的数字\n");
}
}
int main()
{
srand((unsigned)time(NULL)); //以时间戳为种子
int RandNum = rand() % 99; //随机生成0-99的数字
int input = 0;
do {
menu();
printf("请选择:>");
scanf("%d", &input);
switch (input)
{
case 1:
game(RandNum);
break;
case 0:
printf("退出游戏!\n");
break;
default:
printf("输入错误!\n");
break;
}
} while (input);
//printf("%d\n", RandNum);
return 0;
}