其中有些题目用了两种方法,用函数名_1,函数名_2区分开。
(1)输出1-1/2+1/3-...
#include<stdio.h>
double S_1(int n)
{
double sum = 0.0;
int tag = 1;
for (int i = 1; i <= n; i++)
{
sum = sum + 1.0 / i*tag;
tag = tag * (-1);
}
return sum;
}
double S_2(int n)
{
double sum = 0.0;
int tag = -1;
for (int i = 1; i <= n; i++)
{
if (i & 1)
{
sum = sum + 1.0 / i;
}
else
{
sum = sum + (-1) * 1.0 / i;
}
}
return sum;
}
int main()
{
printf("%lf\n", S_1(3));
printf("%lf", S_2(3));
}
(2)输出第n项斐波那契数列
#include<stdio.h>
#define N 100
int fabnic_1(int n)
{
int a[N] = { 1,1 };
int i;
for ( i = 3; i <= n; i++)
{
a[i] = a[i - 1] + a[i - 2];
}
return(a[i - 1]);
}
int fabnic_2(int n)
{
if (n <= 2)
{
return (1);
}
int f1 = 1, f2 = 1,f3;
for (int i = 3; i <= n; i++)
{
f3 = f1 + f2;
f1 = f2;
f2 = f3;
}
}
int main()
{
printf("%d\n", fabnic_1(5));
printf("%d\n", fabnic_2(5));
}
(3)n的阶乘
#include<stdio.h>
int mul_1(int n)
{
int sum = 1;
for (int i = 2; i <= n; i++)
{
sum = sum * i;
}
return sum;
}
int mul_2(int n)
{
if (n == 1)
{
return 1;
}
else
{
return (mul_2(n-1)*n);
}
}
int main()
{
printf("%d", mul_1(5));
printf("%d", mul_2(5));
}
(4)对n开根号
#include<stdio.h>
#include<math.h>
int main()
{
printf("请输入一个小于1000的正数\n");
int n;
scanf_s("%d", &n);
if (n >= 0 && n < 1000)
{
int tmp = (int)sqrt((float)n);
printf("%d", tmp);
}
}
这道题的关键是sqrt的调用条件
int main()
{
int n;
scanf_s("%d", &n);
printf("%d", sqrt(n));
}
输出的结果为0
因为sqrt得到的数一定是double类型,不可用"%d"接收