我做了一個程序,以查找一個數字是否屬於斐波那契數列,如果它確實是它的位置。每當我輸入一個數字if條件出錯。斐波那契!如果一直都是假的
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main(void)
{
int i,x=1,y=1,z,num;
clrscr();
printf("Enter a number to find in fibonacci series:");
scanf("%d",&num);
/*to find if the number is a part of fibonacci series or not*/
if((isdigit(sqrt(5*num*num+4)))||(isdigit(sqrt(5*num*num-4)))) //<-- this if!
{//belongs to fibo!
for(i=1; ;i++)
{
if(x==num)
break;
z=x+y;
x=y;
y=z;
}
printf("%d is the %d term of fibonacci series.",num,i);
}
else
printf("Dear user,The entered number is not a part of the fibonacci series.");
getch();
}
isdigit檢查給定的char是否是一個有效的ascii數字0-9。我不知道你在嘗試使用它。你也真的需要在你的for循環上設置一個上限。 – Lazarus 2010-07-15 15:56:21
查看下面的評論 – 2010-07-15 16:01:41
@Lazarus:迂腐:平方根(一旦固定)的魔術已經在檢查數字是否是斐波那契數。確定後,循環肯定會終止。雖然沒有防守編碼,但該程序在數學上聽起來很合理。 – 2010-07-15 16:04:09