1、计算n的阶乘
//分析:n的阶乘就是1x2x3x4x5x......n
int main()
{
int i = 0;
int n = 0;
int c= 1;
scanf("%d", &n);
for (i = 1;i<= n; i++)
{
c = c* i;
printf("c= %d\n", c);
}
return 0;
}
2、计算1!+2!+3!+…+10!
int main()
{
int i = 0;
int n = 0;
int c= 1;
int sum = 0;
scanf("%d", &n);
for (n = 1; n <= 10; n++)
{
c = 1;//初始化c
for (i = 1; i <= n; i++)
{
c = c * i;
}
sum = sum + c;
}
printf("sum= %d\n", sum);
return 0;
}
//上面代码优化
int main()
{
int i=0;
int n=0;
int c=1;
int sum=0;
for(n=1;n<=10;n++)
{
c=c*n;
sum=sum+c;
}
printf("sum=%d\n",sum);
return 0;
}
3、在一个有序数组中查找具体的某个数字n。编写int binsearch(int x,int v)
//最坏的情况 查找n次
#include<stdio.h>
int main()
{
int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
int k = 7;
//在arr有序数组中找到7
int i = 0;
int sz = sizeof(arr) / sizeof(arr[0]);
for (i = 0; i < sz; i++)
{
if (k == arr[i])
{
printf("找到了,下标是:%d\n", i);
break;
}
}
if (i == sz)
{
printf("找不到\n");
return 0;
}
}
//折半查找(二分查找) 查找log 2^n
int main()
{
int arr[]={1,2,3,4,5,6,7,8,9,10};
int k=7;
int sz=sizeof(arr)/sizeof(arr[0]);//计算元素个数
int high=sz-1;//左下标
int low=0;//右下标
while(low<=high){
int mid=(high+low)/2;
if(arr[mid]>k)
{
high=mid-1;
}
else if(arr[mid]<k)
{
low=mid+1;
}
else
{
printf("找到了,小标是:%d\n",mid);
break; //找到了就停下来
}
}
if(low>high)
{
printf("找不到\n");
}
return 0;
}
4、编写代码,多个字符从两端移动,向中间汇聚
#include<stdio.h>
#include<string.h>
#include<windows.h>
#include<stdlib.h>
//分析,打印效果
//hello word!
//h##########
//h#########!
//he########!
//he#######d! ......
int main()
{
char arr1[] = "hello word!";
char arr2[] = "###########";
int left = 0;
//int sz=sizeof(arr1)/sizeof(arr[0]-1); error 还有/0
//因为 [a b c d \0] [0 1 2 3]
//int sz = sizeof(arr1) / sizeof(arr1[0] - 2); //-2才是感叹号的地址
int right = strlen(arr1) - 1;
while (left<=right)
{
arr2[left] = arr1[left];
arr2[right] = arr1[right];
printf("%s\n", arr2);
//打印一下,休息1s
Sleep(1000);
System("cls");
left++;
right--;
}
return 0;
}
5、编写代码实现,模拟用户登录情景,并且只能登录三次。(只允许输入三次密码,如果密码正确则提示登陆成功,如果三次均错误,则退出程序)
int main()
{
int i=0;
char password[20]={0};
for(i=0;i<3;i++)
{
printf("请输入密码:>");
scanf("%s",password);
//if(password=="123456") ==不能用来比较两个字符串是否相等,应该使用一个库函数——strcmp
if(strcmp(password,"123456")==0)
{
printf("登陆成功\n");
break;
}
}
if(i==3)
printf("三次密码均错误,请退出程序\n");
return 0;
}