用c语言怎么编程?
发布网友
发布时间:2022-04-22 21:35
我来回答
共3个回答
热心网友
时间:2023-08-19 08:35
我的算法没有那位用数列的高效,但可以由用户输入n来确定计算前n项的和
#include<stdio.h>
#include<stdlib.h>
int fa(int n)
{
int a;
if(0==n||1==n)
a=1;
else
a=fa(n-1)+fa(n-2);
return a;
}
int fb(int n)
{
int b;
if(0==n) b=1;
else if(1==n) b=3;
else b=fa(n)+fb(n-1);
return b;
}
main()
{
FILE *fp;
int n,a,b,c,i;
float d,s;
s=0.0;
c=1;
printf("Please enter integer n=");
scanf("%d",&n);
if(n<0) exit(0);
if((fp=fopen("cac.txt","w"))==NULL)
printf("The result cannot be saved.\n");
else
printf("The result is saved as cac.txt\n");
for(i=0;i<n;i++)
{
a=fa(i);
b=fb(i);
fprintf(fp,"%d/%d",a,b);
printf("%d/%d",a,b);
if(i<n-1)
{
if(c>0)
{
fputs("-",fp);
printf("-");
}
else
{
fputs("+",fp);
printf("+");
}
}
else
{
fputs("=",fp);
printf("=");
}
d=((float)c)*((float)a)/((float)b);
s=s+d;
c=c*(-1);
}
fprintf(fp," %f",s);
printf(" %f\n",s);
fclose(fp);
}
热心网友
时间:2023-08-19 08:35
#include<stdio.h>
#define exp 1e-6
#define max 64
double fib[max];
int main(void)
{
int i; fib[0] = fib[1] = 1.0;
for(i = 2; i < max; i++)
fib[i] = fib[i - 1] + fib[i - 2];
double ans = 1.0;
for(i = 3; i < max ;i++)
{
double index = fib[i - 2] / fib[i];
if(i & 1) index = -index;
//printf("%.2f %.2f %.2f\n", fib[i - 2], fib[i], index);
ans += index;
}
printf("%f\n", ans);
return 0;
}
热心网友
时间:2023-08-19 08:36
这个在百度上面有,我就不复制了追问不一样 我的分子分母是fibonacci数列