1.计算n的阶乘
int main()
{
int n = 0;
int i = 0;
int num = 1;
printf("Input num:\n");
scanf_s("%d", &n);
for (i = 1; i < n+1; i++)
{
num = i * num;
}
printf("Output:%d\n", num);
return 0;
}
2.计算1-10的阶乘和它们的和
int main()
{
int n = 0;
int i = 1;
int num = 1;
int sum = 0;
printf("Input num:\n");
scanf_s("%d", &n);
for (i = 1; i < n+1; i++)
{
num = i * num;
sum += num;
}
printf("Output:%d\n", num);
printf("Output num:%d\n", sum);
return 0;
}
----------------------------------------------------------------------------------------
int main()
{
int i = 1;
int num = 1;
int sum = 0;
for (i = 1; i < 11; i++)
{
num = i * num;
sum += num;
}
printf("Output num:%d\n", sum);
return 0;
}
3.在一个有序数组中查找具体的某个数字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 left = 0;
int right = sz-1;
while (left<=right)
{
int mid = (left + right) / 2;
arr[mid];
if (arr[mid] < k)
{
left = mid + 1;
}
else if (arr[mid] > k)
{
right = mid - 1;
}
else
{
printf("Find:%d\n", mid);
break;
}
}
if (left>right)
{
printf("Not find!");
}
return 0;
}
函数形式
int binary_search(int a[], int k, int s)
//a[]中间不设范围,是因为传递过来的仅仅是首元素地址,设置范围也没有用
{
int left = 0;
int right = s - 1;
while (left <= right)
{
int mid = (left + right) / 2;
if (a[mid] > k)
{
right = mid - 1;
}
else if (a[mid] < k)
{
left = mid + 1;
}
else
{
return mid;
}
}
return -1;
}
int main()
{
int arr[20] = { 1,2,3,4,5,6,7,8,9,10 };
int key = 7;
int sz = sizeof(arr) / sizeof(arr[0]);//sz是为了控制下标
//找到了就返回找到的位置的下标
//找不到返回-1
//数组arr[]传参其实不是传递的数组本身,仅仅是数组首元素地址
int ret = binary_search(arr,key,sz);
if (-1 == ret)
{
printf("Not find.\n");
}
else
printf("Find:下标是%d", ret);
return 0;
}
4.编写代码,演示多个字符从两端移动,向中间汇聚。
int main()
{
char arr1[] = "Welcome!!!";
char arr2[] = "##########";
int left = 0;
int right = strlen(arr1)-1; //头文件:#include<string.h>
while (left <= right)
{
arr2[left] = arr1[left];
arr2[right] = arr1[right];
printf("%s\n", arr2);
Sleep(1000);//睡眠1秒 头文件:#include<Windows.h>
system("cls");//清空屏幕 头文件:#include<stdlib.h>
left++;
right--;
}
printf("%s\n", arr2);
return 0;
}
5.编写代码,实现模拟用户登录场景,并且只能登录三次。
(只允许输入三次密码,如果密码正确则提示登录成功,如果三次均输错,则退出程序。)
int main()
{
int i = 0;
char password[20] = { 0 };
//假设正确的密码是字符串“123456”
for (i = 0; i < 3; i++)
{
printf("Please input password:");
scanf_s("%s", password,sizeof(password));
//if(password=="123456")
//eer---两个字符串比较,不能使用==,应该使用strcmp(字符串比较函数)
//因为==比较的是字符串的首字母的地址
if (strcmp(password,"123456")==0)
{
printf("Success!\n");
break;
}
else
{
printf("Password is wrong.Again!\n");
}
}
if (i == 3)
printf("Three times.Fail!\n");
return 0;
}