程序一、求第n個斐波那契數。
#include <stdio.h>
#define max 10000
main()
{
long a[max];
a[0]=1;
a[1]=1;
int n,i;
int t=0;
printf("Please input a number:\n");
scanf("%ld",&n);
if(n==1||n==2)
printf("the fei bo na qi shu is %ld.\n",a[n-1]);
else
{
for(i=2;i<n;i++)
{
a[i]=a[i-1]+a[i-2];
t=a[i];
}
printf("the fei bo na xi shu is %ld.\n",t);
}
return 0;
}
程序二、輸入一個n型整數,求出其二進制形式中的1的個數。
#include <stdio.h>
void to_binary(int);
int main()
{
int n;
printf("Please input a number(q to quit);\n");
while(scanf("%d",&n)==1)
{
printf("Binary equivalent:");
to_binary(n);
printf("\n");
printf("Please input another number:\n");
}
return 0;
}
void to_binary(int n)
{
int t,num;
num=0;
while(n>=2)
{
t=n%2;
if(t==1)
num++;
n=n/2;
putchar('0'+t);
}
if(n==1)
{
putchar('0'+1);
num++;
}
else
putchar('0'+0);
printf("\nthe number of one is %d.\n",num);
return ;
}
問題:程序中想輸出二進制,但輸出來的數是反的?
解決輸出問題:採用遞歸的辦法
void to_binary (int n)
{
int r;
r=n%2;
if(n>=2)
{
to_binary(n/2);
}
putchar('0'+r);
return;
}
這個辦法能輸出一個數的二進制形式,但一的個數沒法求出來,有待解決。
程序三、求出1000以內所有的完數。
#include <stdio.h>
int main()
{
int n=1000;
int i,r,j;
printf("the number from 1-1000 wanshu is:\n");
for(i=1;i<=1000;i++)
{
r=0;
for(j=1;j<i;j++)
{
if(i%j==0)
r+=j;
}
if(r==i)
printf("%d ",i);
}
printf("\n");
return 0;
}