1、求第n个斐波那契数。
#include <stdio.h>
int main()
{
int n;
inti;
intf_num[100];
f_num[0]=0;
f_num[1]=1;
printf("Pleaseinput a num(q to quit): ");
while(scanf("%d",&n))
{
if(n>1)
{
for(i=2;i<n;i++)
{
f_num[i]=f_num[i-1]+f_num[i-2];
}
printf("The f_num is%d\n",f_num[i-1]);
}
else
printf("Thef_num is %d\n",f_num[n]);
printf("Please input a num(q to quit):");
}
printf("Done!\n");
return 0;
}
注意:while(scanf("%d",&n))的必要性
2、输入一个int型整数,求出其二进制形式中1的个数。
#include <stdio.h>
int main()
{
int n;
intcount=0;
printf("Pleaseinput a num(int): ");
scanf("%d",&n);
while(n>0)
{
if(n%2==1)
count++;
n=n/2;
}
printf("theone in it's binary system are %d.\n",count);
return 0;
}
3、求出1000以内的完数。
#include <stdio.h>
int main()
{
int n;
inti;
intsum=0;
for(n=3;n<1000;n++)
{
for(i=1;i<n;i++)
{
if(n%i==0)
sum+=i;
}
if(sum==n)
printf("%d ",n);
sum=0;
}
printf("\n");
return 0;
}
注意:对n和i赋予的初始值,还有sum重置为0(sum=0;)