目录
注意:在求和时,如果不将sum每次求和的初始值置为1,那么求和就会重复。
求n!
int main() {
int n = 0;
int sum = 1;
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
sum = sum * i;
//sum *=i;
}
printf("%d\n",sum);
return 0;
}
第二题1!+2!+...+n!
正常求和,1+1*2+1*2*3......
每一重置sum:1+1+1*2+1+1*2+1*2*3+1+1*2+1*2*3+1*2*3*4
//第二题1!+2!+...+n!
int main() {
int n = 0;
scanf("%d", &n);
int sum = 1;
int cum = 0;
for(int i = 1;i<=n;i++) //要循环两次
{
sum = 1; //让sum每次置为1
for (int j = 1; j <= i; j++)
{
sum = sum * j;
}
cum = cum + sum;
}
/*for (int i = 1; i <= n; i++) {
sum *= i;
cum += sum;
}*/
printf("%d", cum);
return 0;
}
?在有序数组1,2,3,4,5,6,7,8,9,10里查找元素
printf("%d\n", sizeof(arr));? ? //求数组的大小
?? ?printf("%d\n", sizeof(arr[0]));? ? ? ? //求数组一个元素的大小
?? ?printf("%d\n", sizeof(arr) / sizeof(arr[0])? ? ? ? ?//求数组的元素个数
?这里用到sizeof函数,可以求出数组的大小
//第三题 在有序数组里查找元素
方法一遍历查找
int main() {
int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
printf("%d\n", sizeof(arr));
printf("%d\n", sizeof(arr[0]));
printf("%d\n", sizeof(arr) / sizeof(arr[0]));
int n = 0;
scanf("%d", &n);
int i=0;
while (i<=10) {
if (arr[i] != n) {
i++;
}
else {
printf("找到了,下标为%d", i);
break;
}
}
return 0;
}
?用一个变量left表示第一个元素,一个变量right表示最后一个元素。
数组的下标是从0开始的,所以right的值应该是数组长度-1;
//方法二折半查找
int main(){
int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
int n = 0;
scanf("%d", &n);
int tp = sizeof(arr) / sizeof(arr[0]);
int left = 0;
int right = tp - 1;
int mid = (left + right) / 2;
while (left <= right) {
mid = (left + right) / 2;
if (n > arr[mid]) {
left = mid + 1;
}
else if (n < arr[mid]) {
right = mid - 1;
}
else {
printf("找到了下标为%d",mid);
break;
}
}
return 0;
}
从两头向中间移动,生成相应的字符串
如将 welcome to China !!!,从两头向中间输出
输出结果如下?
#define _CRT_SECURE_NO_WARNINGS
#include<stdlib.h>
#include<stdio.h>
//第四题
int main() {
//方法一
char arr1[] = "welcome to China!!!";
char arr2[] = "*******************";
int tp = sizeof(arr1) / sizeof(arr1[0]);
int left = 0;
int right = tp - 1;
while (left <= right) {
arr2[left] = arr1[left];
arr2[right] = arr1[right];
left++;
right--;
printf("%s\n", arr2);
}
return 0;
}