1

我编写了一个程序来查找一个数字是否属于斐波那契数列,以及它的位置是什么。每当我输入一个数字时,如果条件出错。

#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();
}
4

4 回答 4

7

你误解了isDigit函数

isDigit接受 ASCII 字符代码,如果它表示十进制数字,则返回 true。

您要检查double返回的 bysqrt是否为整数。

于 2010-07-15T15:55:19.407 回答
3

您在使用isdigit(). 该函数(通常是宏)用于判断字符是否是字符之一0.. 9- 当然,您的代码始终在处理数字,并且不需要字符检查。

你会想仔细看看你想要完成什么。欢迎您询问我们哪些 C 函数可能是合适的。


编辑:

啊,你想知道那个时髦的表达式是否是一个整数值。唉,没有内置的功能。我没有测试过这个,但我会写

double a = (funky expr);
if (a == rint(a)) ...

...其中rint()是一个函数,它返回与double给定参数最接近的整数值。

于 2010-07-15T15:56:02.703 回答
1

你为什么用isdigit?sqrt 的结果是double- 您需要直接检查该值。

于 2010-07-15T15:57:39.840 回答
0

你想检查是否5 * num * num + 45 * num * num - 4是一个完美的正方形。执行此操作的函数是:

int is_perfect_sq(double d)
{
    double sqroot = rint(sqrt(d));

    return (sqroot * sqroot) == d;
}

注意 - 这很好地反驳了您永远不应该比较浮点数是否相等的概念。在这种情况下,这很好,因为“完美正方形”必须是整数。

于 2010-07-16T05:12:03.453 回答