第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;
}
