目录
?1.计算n的阶乘
2.计算 1!+2!+3!+……+10!?
?3. 在一个有序数组中查找具体的某个数字n。 编写int binsearch(int x, int v[], int n);?功能:在v[0]<= v[1] <= v[2] <= …. <= v[n - 1]的数组中查找x
4. 编写代码,演示多个字符从两端移动,向中间汇聚。?
?5. 编写代码实现,模拟用户登录情景,并且只能登录三次。只允许输入三次密码,如果密码正确则提示登录成,如果三次均输入错误,则退出程序。
?1.计算n的阶乘
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
int main()
{
int i = 0;
int ret = 1;
int n = 0;
scanf("%d", &n);
for (i = 1; i <= n; i++)
{
ret = ret * i;
}
printf("%d", ret);
return 0;
}
2.计算 1!+2!+3!+……+10!?
#include<stdio.h>
int main()
{
/*int i = 0;
int n = 0;
int sum = 0;
int ret = 1;
for (n = 1; n <= 10; n++)
{
ret = 1;//易错点 需要重置ret = 1
for (i = 1; i <= n; i++)
{
ret = ret * i;//n的阶乘
}
sum = ret + sum;
}
printf("sum = %d", sum);*///两个循环 效率不高
//改进
/*int i = 0;
int n = 0;
int sum = 0;
int ret = 1;
for (n = 1; n <= 10; n++)
{
ret = ret * n;//n的阶乘
sum = ret + sum;
}
printf("sum = %d", sum);*/
return 0;
}
?3. 在一个有序数组中查找具体的某个数字n。 编写int binsearch(int x, int v[], int n);?功能:在v[0]<= v[1] <= v[2] <= …. <= v[n - 1]的数组中查找x
#include<stdio.h>
int main()
{
/*int arr[] = {1,2,3,4,5,6,7,8,9};
int i = 0;
int k = 17;
int sz = sizeof arr / sizeof arr[0];
for (i = 0; i < sz; i++)
{
if (k == arr[i])
{
printf("找到了,下标为:%d\n", i);
break;
}
}
if (sz == i)
printf("没找到");*///对于有序数组,不够高效
//改进---折半查找算法
/*int arr[] = {1,2,3,4,5,6,7,8,9};
int k = 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)
{
right = mid - 1;
}
else if (arr[mid] < k)
{
left = mid + 1;
}
else
{
printf("找到了,下标为:%d\n", mid);
break;
}
}
if (left > right)
printf("没找到");*/
return 0;
}
4. 编写代码,演示多个字符从两端移动,向中间汇聚。?
#include<stdio.h>
#include<string.h>
#include<Windows.h>//Sleep()
#include<stdlib.h>//system()
int main()
{
char arr1[] = "welcome to Chain!!!";
char arr2[] = "###################";
int left = 0;
int right = sizeof(arr1) / sizeof(arr1[0]) - 2;//"welcome to Chain!!!"--welcome to Chain!!!\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", arr2);
return 0;
}
?5. 编写代码实现,模拟用户登录情景,并且只能登录三次。只允许输入三次密码,如果密码正确则提示登录成,如果三次均输入错误,则退出程序。
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
int main()
{
int i = 0;
char password[20] = {0};
for (i = 1; i <= 3; i++)
{
printf("请输入密码:>");
scanf("%s", password);
if(strcmp(password, "123456") == 0)//比较两个字符串不能用==,应该使用库函数strcmp
{
printf("登陆成功\n");
break;
}
else
{
printf("密码错误\n");
}
}
if(3 == i)
{
printf("三次密码均错误,退出程序\n");
}
return 0;
}
|