我做了一个程序来查找一个数字是否属于斐波那契系列,如果它确实是它的位置。当我输入一个数字时,如果条件出错了。
#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();
}
答案 0 :(得分:7)
答案 1 :(得分:3)
使用isdigit()
时出现明显错误。该函数(通常是宏)用于判断字符是否是0
... 9
中的一个字符 - 当然,您的代码始终处理数字并且不需要进行字符检查。
您需要仔细研究一下您要完成的任务。欢迎您向我们询问哪些C函数可能适用。
编辑:
啊,你想知道那个时髦的表达式是否是一个整数值。唉,这里没有内置功能。我没有测试过这个,但是我写了
double a = (funky expr);
if (a == rint(a)) ...
...其中rint()
是一个函数,它返回给定参数的最近整数值double
。
答案 2 :(得分:1)
您为什么使用isdigit
? sqrt的结果是double
- 您需要直接检查该值。
答案 3 :(得分:0)
您想要检查5 * num * num + 4
或5 * num * num - 4
是否是完美的正方形。执行此操作的功能是:
int is_perfect_sq(double d)
{
double sqroot = rint(sqrt(d));
return (sqroot * sqroot) == d;
}
注意 - 这是一个很好的反对意见,你应该永远比较浮点数是否相等。在这种情况下,它很好,因为“完美的正方形”必须是整数。