内容:
1:计算 n的阶乘
2:1!+2!+.......+10!
#include <stdio.h>
int main()
{
int i = 0;
int n = 0;
int ret = 1;
int sum = 0;
for (n = 1; n <= 3; n++)
{
ret = 1;//没有ret=1这个条件就会使得ret具有累积效果,当n=3时,原先的ret=2被保留了下来,for进入
//计算就是ret=2*1(i=1),ret=2*2(i=2),ret=2*2*3=12(i=3)ret就被赋值到15
for (i = 1; i <= n; i++)
ret = ret * i;
sum = sum + ret;
}
printf("sum=%d ", sum);
return 0;
3:在一个有序数组中查找某一个数字n
方法(二分查找法,高效快捷,效率为是log)不断地查找中间值,然后一直缩小范围来找到向查找的数。
#include <stdio.h> int main() { int arr[] = { 1,2,3,4,6,7,8,9,12,15,16 }; int left = 0;//左下标 int i = 66;//查找值 int sz = sizeof(arr) / sizeof(arr[0]);//元素个数 int right = sz - 1;//右下标
while (left <= right)
{
int mid = (left + right) / 2;//如果不将mid拿入while循环,那么就无法进行查找
if (arr[mid] < i)
{
left = mid + 1;
}
else if (arr[mid] > i)
{
right = mid - 1;
}
else
{
printf("找到了,下标是:%d\n", mid);
break;
}
}
if (left > right)
printf("找不到\n");
return 0;
}
4:编写代码,多个字符由两边向中间汇聚。
#include <stdio.h>
#include <string.h>
#include <windows.h>
#include <stdlib.h>
int main()
{
char arr1[] = "welcome to beihua!!!!";
char arr2[] = "#####################";
int left = 0;
int right = strlen(arr1) - 1;
while (left <= right)
{
arr2[left] = arr1[left];
arr2[right] = arr1[right];
printf("%s\n", arr2);
Sleep(1000);
system("cls");
left++;
right--;
}
printf("%s\n", arr1);
return 0;
}