Educoder-程序设计基础:函数
第1关:求和
题目描述:给你一个n
,要求你编写一个函数求1+2+.......+n
#include<stdio.h>
int fact(int x)
{
int m, sum = 0;
for (m = 1; m <= x; m++)
sum += m;
return sum;
}
int main()
{
int x;
scanf("%d", &x);
printf("%d", fact(x));
return 0;
}
第2关:回文数计算
本关任务:编写函数求区间[200,3000]
中所有的回文数,回文数是正读和反读都是一样的数。如525
, 1551
#include<stdio.h>
int fact(int x)
{
int a = 0;
while (x) //x==1
{
a = a * 10 + x % 10;
x = x / 10; //x=0时会终止循环
}
return a;
}
int main()
{
int m;
for (m = 200; m <= 3000; m++)
if (fact(m) == m)
{
printf("%d\n", m);
}
return 0;
}
第3关: 编写函数求表达式的值
题目描述:有如下表达式 s = 1 + 1 / 3 + (1 * 2) / (3 * 5) + (1 * 2 * 3) / (3 * 5 * 7) + .... + (1 * 2 * 3 * .... * n) / (3 * 5 * 7 * ... * (2 * n + 1))
。编写函数求给出的n所对应的表达式s的值
#include<stdio.h>
double a(double b)
{
double s, c, d, i;
s = 1;
c = 1;
d = 1;
for (i = 0; i <= b; i++)
{
c = c * i;
d = (2 * i + 1) * d;
s = c / d + s;
if (c == 0)
c = 1;
}
return s;
}
int main(void)
{
int b;
scanf("%d", &b);
printf("%.10lf", a(b));
return 0;
}
第4关:阶乘数列
题目描述:求Sn=1!+2!+3!+4!+5!+…+n!
之值,其中n
是一个数字
#include<stdio.h>
long long fact(int a)
{
int i;
long long b, c;
b = 0;
c = 1;
for (i = 1; i <= a; i++)
{
c = i * c;
b = b + c;
}
return b;
}
int main(void)
{
int a;
scanf("%d", &a);
printf("%ld", fact(a));
return 0;
}
第5关:亲密数
题目描述:两个不同的自然数A
和B
,如果整数A
的全部因子(包括1
,不包括A
本身)之和等于B
;且整数B的全部因子(包括1
,不包括B
本身)之和等于A
,则将整数A
和B
称为亲密数。求3000
以内的全部亲密数
#include<stdio.h>
void solve() {
int i, a, b1, b2;
for (a = 1; a < 3000; a++)
{
b1 = 0;
for (i = 1; i <= a / 2 + 1; i++)
if (a % i == 0)b1 += i;
b2 = 0;
for (i = 1; i < b1 / 2 + 1; i++)
if (b1 % i == 0)b2 += i;
if (b2 == a && a < b1)
printf("(%d,%d)", a, b1);
}
}
int main(void)
{
solve();
return 0;
}
第6关:公约公倍数
题目描述:写两个函数,分别求两个整数的最大公约数和最小公倍数,用主函数调用这两个函数,并输出结果。两个整数由键盘输入
#include<stdio.h>
long long a(long x, long y)
{
long b = 0, i;
for (i = 1; i <= x; i++)
{
if (x % i == 0 && y % i == 0)
b = i;
}
return b;
}
long long b(long x, long y)
{
long d = 0, i, c;
for (i = 1; i <= x; i++)
{
if (x % i == 0 && y % i == 0)
{
d = i;
}
}
c = d * (x / d) * (y / d);
return c;
}
int main(void)
long x, y, z;
scanf("%ld%ld", &x, &y);
if (x > y)
{
z = x;
x = y;
y = z;
}
if (x < 0 || y < 0)
{
printf("Input Error");
return 0;
}
printf("%ld ", a(x, y));
printf("%ld", b(x, y));
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?