#include<stdio.h>
int main()
{
int a = 1;
int num = 1;
int n = 0;
scanf("%d", &n);
for (a = 1; a <= n; a++)
{
num = num * a;
}
printf("%d\n", num);
return 0;
}
2. 计算1!+2!+3!+……+n!
#include<stdio.h>
int main()
{
int a = 1;
int num = 1;
int n = 0;
int ret = 0;
scanf("%d", &n);
for (a = 1; a <= n; a++)
{
num = num * a;
ret = ret + num;
}
printf("%d\n", ret);
return 0;
}
3.用二分法查找数据(注:查找的单元一定为有序数组)
#include<stdio.h>
int main()
{
int ch[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int i = 0;
printf("请输入要查询的数字:");
scanf("%d", &i);
int lg = sizeof(ch) / sizeof(ch[0]);
int left = 0;
int right = lg - 1;
while (left <= right)
{
int mid = (left + right) / 2;
if (i < ch[mid])
{
right = mid - 1;
}
else if (i > ch[mid])
{
left = mid + 1;
}
else
{
printf("找到了,下表为:%d", mid);
break;
}
}
if (left > right)
{
printf("出错啦");
}
return 0;
}
4.电脑生成一个1~100的随机数,进行猜测
#include <stdio.h>
#include<stdlib.h>
#include<time.h>
void statrgame()
{
printf("####################\n");
printf("##### 1.play #####\n");
printf("##### 0.exit #####\n");
printf("####################\n");
}
void game()
{
int guss = 0;
//1.生成随机数字 rand生成的随机数的范围为0~32767
int ret = rand() % 100 + 1; //生成随机数的范围被订到了0~100
//2.猜数字
while (1)
{
printf("开始猜数字了");
scanf("%d", &guss);
if (guss < ret)
{
printf("猜小了\n");
}
else if (guss > ret)
{
printf("猜大了\n");
}
else
{
printf("猜对了\n");
break;
}
}
}
int main()
{
int input = 0;
srand((unsigned int)time(NULL)); //设置一个随机数的起点,这里我们就需要用到time函数,因为时间是不断在变化的,
//所以我们得在srand中传递一个时间,也就是时间戳,time函数需要引用头文件<time.h>。time()后面我们不需要赋值,
// 所以给个空值NULL,而srand函数需要一个unsigned int类型的值,所以我们要强制把time返回成unsigned int类型。
//time函数返回一个时间戳
do
{
statrgame();
printf("请做出你的选择");
scanf("%d", &input);
switch (input)
{
case 1:
game();
break;
case 0:
printf("退出游戏");
break;
default:
printf("选择错误,重新输入\n");
break;
}
} while (input);
return 0;
}