写代码的思路:
办法(编程思维)+写代码(按照语法形式写)
编程思维:需要慢慢训练
1、计算n的阶乘
代码1:
int main()
{
int i = 1;
int n = 0;
scanf("%d", &n);
int ret = 1;
do
{
ret=ret*i;
i++;
} while (i<=n);
printf("%d\n", ret);
return 0;
}
代码2:
int main()
{
int i = 1;
int n = 1;
scanf("%d", &n);
int r = 1;
for (i = 1; i <= n; i++)
{
r = r * i;
}
printf("%d\n", r);
return 0;
}
2、 计算1!+2!+3!.....+10!
代码1:
int main()
{
int i = 1;
int j = 1;
int r = 1;
int sum = 0;
for (i = 1; i <= 10; i++)
{
r = 1; //必须注意每次都要将r初始化为1,不然下一次循环的阶乘会直接在之前的基础上计算
for (j = 1; j <= i; j++)
{
r = r * j;
}
sum = sum + r;
}
printf("%d\n", sum);
return 0;
}
代码2:(优化)
int main()
{
int sum = 0;
int i = 0;
int r = 1;
for (i = 1; i <= 10; i++)
{
r = r * i;
sum = sum + r;
}
printf("%d\n", sum);
return 0;
}
3、在一个有序数组中查找具体的某个数字n(二分查找)
代码1:遍历查找
int main()
{
int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
int sz = sizeof(arr) / sizeof(arr[0]);
int num = 0;
scanf("%d", &num);
int i = 0;
for (i = 0; i < sz; i++)
{
if (num == arr[i])
{
printf("找到了,下标是%d\n",i);
break; //找到后,无需继续遍历
}
}
if (sz == i)
{
printf("找不到\n");
}
return 0;
}
代码2:二分查找(折半查找)
注:前提条件:数字是有序的
解释:
设置左下标left,右下标right,中间下标mid,目标数为k
左下标最初为0,右下标最初为sz-1,中间下标为(左下标+右下标)/2
将arr[mid]与k相比:
arr[mid]>k,right=mid-1
arr[mid]<k,left=mid+1
重新计算mid,与k进行比较,直到left>right为止
图解:以目标数为7举例
代码如下:
int main()
{
int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
int sz = sizeof(arr) / sizeof(arr[0]);
int num = 0;
scanf("%d", &num);
int left = 0;
int right = sz - 1;
int i = 0;
while(left<=right) //只有左下标<=右下标,才有可能找到
{
int mid = (left + right) / 2;
if (arr[mid] < num)
{
left = mid + 1;
}
else if (arr[mid] > num)
{
right = mid - 1;
}
else
{
printf("找到了,下标是%d\n", mid);
break;
}
}
if (left > right)
printf("找不到\n");
return 0;
}