首页 > 解决方案 > 如何处理返回值 inf

问题描述

我自己完成了一本关于 C 的书。这不是要上交的作业。我正在编写一个 C 程序来确定我的机器可以产生的最大斐波那契数。并指示使用非递归方法。

我的代码:

#include<stdio.h>
double fibo(int n);
int main(void)
{
    int n = 0; // The number input by the user
    double value; // Value of the series for the number input

    while (n >= 0)
    {

       // Call fibo function

       value = fibo(n);

       // Output the value

       printf("For %d the value of the fibonacci series = %.0f\n", n, 
       value);


       n++;

    }

   return 0;
}

double fibo(int n)
{

  int i; // For loop control variable
  double one = 0; // First term
  double two = 1; // Second term
  double sum = 0; // placeholder

  if (n == 0)
      return 0;
  else if (n == 1)
      return 1;
  else
  {
     for (i = 2; i <= n; i++)
     {
        sum = one + two;
        one = two;
        two = sum;
     }
  }

return sum;

代码工作正常,但我想在输出给我第一个实例时中断:

For 17127 the value of the fibonacci series = inf

有没有办法给我们一个 if 语句,例如:

if (value == inf)
  break;

标签: cfloating-pointbreak

解决方案


最简单的是使用INFINITYisinf()


推荐阅读