计算n的阶乘(先不考虑溢出)

#include <stdio.h>
int main()
{
    int n;
    int i = 1;
    int s = 1;
    printf("请输入n:\n");
    scanf("%d", &n);
    for (i = 1; i <= n; i++)
    {
        s = s * i;

    }
    printf("%d!=%d\n", n, s);
}

计算1!+2!+3!+......+10!

#include <stdio.h>
int main()
{
	int i = 0;
	int n = 0;
	int ret = 1;
	int sum = 0;
	for (n = 1; n <= 10, n++)
	{
		for (i = 1; i <= n; i++)
		{
			ret = ret * i;
		}
		sum = sum + ret;
	}
	printf("%d\n",sum);
	return 0;
}

以上代码问题出在哪里?

答:ret未初始化,每一次循环ret都应该从1乘起

#include <stdio.h>
int main()
{
	int i = 0;
	int n = 0;
	int ret = 1;
	int sum = 0;
	for (n = 1; n <= 10, n++)
	{
		ret = 1;//添加此行
		for (i = 1; i <= n; i++)
		{
			ret = ret * i;
		}
		sum = sum + ret;
	}
	printf("%d\n",sum);
	return 0;
}

然而这样并不是最优方法,如计算之后数的阶乘时没有必要从1重新开始

#include <stdio.h>
int main()
{
	int i = 0;
	int n = 0;
	int ret = 1;
	int sum = 0;
	for (n = 1; n <= 10; n++)
	{
		ret = ret * n;
		sum = sum + ret;
	}
	printf("%d\n", sum);
	return 0;
}

在有序数组中查找数字

#include <stdio.h>
int main()
{
	int arr[] = {1,2,3,4,5,6,7,8,9,10};
	int k = 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;
}

既然是有序的,则以上方法不够高效,引入二分法

#include <stdio.h>
int main()
{
	int k = 7;
	int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
	int sz = sizeof(arr) / sizeof(arr[0]);
	int l = 0;//左下标
	int r = sz-1;//右下标
	
	while (l <= r)
	{
		int mid = (l + r) / 2;
		if (arr[mid] > k)
		{
		r = mid - 1;
		}
		else if (arr[mid] < k)
		{
		l = mid + 1;
		}
		else
		{
		printf("找到数字,下标为%d\n", mid);
		break;
		}
	}
	if (l > r)
		printf("找不到数字\n");
	return 0;
}

多个字符从两端移动向中间汇聚

#include <stdio.h>
#include <string.h>
#include <windows.h>
#include <stdlib.h>
int main()
{
	char arr1[] = "welcome to my blog";
	char arr2[] = "##################";
	int l = 0;
	//int r = sizeof(arr1) / sizeof(arr1[0]) - 2;
	int r = strlen(arr1)-1;
	while (l<=r)
	{
		arr2[l] = arr1[l];
		arr2[r] = arr1[r];
		printf("%s\n", arr2);
		Sleep(150);
		system("cls");
		l++;
		r--;
	}
	return 0;
}

简单登录,密码三次均错误退出

#include <stdio.h>
int main()
{
	int i = 0;
	char passwd[20] = { 0 };
	for (i = 0; i < 3; i++)
	{
		printf("请输入密码:");
		scanf("%s", passwd);
		if (passwd == "123456")
		{
			printf("登录成功\n");
				break;
		}
	}
	if (i == 3)
		printf("退出\n");
	return 0;
}

以上做法是否正确?

调试后发现并非如此,输入123456没有成功

原因:==不能用来比较两个字符串是否相等,应使用库函数strcmp

#include <stdio.h>
int main()
{
	int i = 0;
	char passwd[20] = { 0 };
	for (i = 0; i < 3; i++)
	{
		printf("请输入密码:");
		scanf("%s", passwd);
		if (strcmp(passwd , "123456")==0)
		{
			printf("登录成功\n");
			break;
		}
	}
	if (i == 3)
		printf("退出\n");
	return 0;
}


我们所度过的每个平凡的日常,也许就是连续发生的奇迹