1.计算n的阶乘
用for比较好
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main()
{
int i = 1;
int n = 0;
int sum = 1;
scanf("%d", &n);
for (i = 1;i <= n;i++)
{
sum *= i;
}
printf("%d\n", sum);
return 0;
}
2.计算1!+2!+3!+……+10!
笨方法:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main()
{
int i = 0;
int n = 0;
int sum1 = 1;
int sum2 = 0;
for (n = 1;n <= 10; n++)
{
sum1 = 1;//每次开始前都要初始为1
for (i = 1;i <= n; i++)
{
sum1 *= i;
}
sum2 += sum1;
}
printf("%d\n", sum2);
return 0;
}
改进:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main()
{
int i = 0;
int n = 0;
int sum1 = 1;
int sum2 = 0;
for (n = 1; n <= 10; n++)
{
sum1 *= n;
sum2 += sum1;
}
printf("%d\n", sum2);
return 0;
}
3.在一个有序数组中查找一个数字n
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main()
{
int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
int k = 7;
//在arr找7
int sz = sizeof(arr) / sizeof(arr[0]);//计算一个元素的大小
int left = 0;
int right = sz - 1;
while (left <= right)
{
int mid = (left + right) / 2;
if (arr[mid] < k)
{
left = mid + 1;
}
else if (arr[mid] > k)
{
right = mid - 1;
}
else
{
printf("找到了,下表是:%d\n", mid);
break;
}
if (left > right)
{
printf("找不到了\n");
}
}
return 0;
}