阶乘,二分查找,字符移动
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了阶乘,二分查找,字符移动相关的知识,希望对你有一定的参考价值。
输出n的阶乘
#include<stdio.h>
#include<Windows.h>
#pragma warning(disable:4996)
int Fact(int n)
{
int ret = 1;
for (int i = 1; i <= n; i++)
{
ret *= i;
}
return ret;
}
int main()
{
int n = 5;
int result=Fact(n);
printf("%d
", result);
system("pause");
return 0;
}
输出1!+2!+3!的和
#include<stdio.h>
#include<Windows.h>
#pragma warning(disable:4996)
int Fact(int n)
{
int ret = 1;
for (int i = 1; i <= n; i++)
{
ret *= i;
}
return ret;
}
int Factsum(int n)
{
int sum = 0;
for (int i = 1; i <= n; i++)
{
sum += Fact(i);
}
return sum;
}
int main()
{
int n = 3;
printf("%d
", Factsum(n));
system("pause");
return 0;
}
在一个升序数组中查找具体的某个数字
#include<stdio.h>
#include<Windows.h>
#pragma warning(disable:4996)
int Binsearch(int arr[], int num, int target)
{
int start = 0;
int end = num - 1;
while (start <= end)
{
int mid = start+(end - start) / 2;
if (target < arr[mid])
{
end = mid - 1;
}
else if (target>arr[mid])
{
start = mid + 1;
}
else return mid;
}
return -1;
}
int main()
{
int arr[] = { 11, 22, 33, 44, 55, 66, 77, 88 };
int target = 77;
int num = sizeof(arr) / sizeof(arr[0]);
int ret=Binsearch(arr, num, target);//找到返回数组下标,未找到返回-1
if (ret == -1)
{
printf("未找到!
");
}
else
{
printf("%d
", arr[ret]);
}
system("pause");
return 0;
}
演示多个字符从两端移动,向中间汇聚
#include<stdio.h>
#include<Windows.h>
#pragma warning(disable:4996)
void show()
{
char lable[]="########################";
char content[]="hello world,hello china!";
int len= strlen(content);
int start = 0;
int end = 0;
for (start = 0, end = len - 1; start <= end; start++, end--)
{
printf("%s
", lable);
lable[start]=content[start];
lable[end]=content[end];
printf("%s
", lable);
}
}
int main()
{
show();
system("pause");
return 0;
}
以上是关于阶乘,二分查找,字符移动的主要内容,如果未能解决你的问题,请参考以下文章
go 实现几个递归经典案例(阶乘斐波那契数列二分查找汉诺塔)