c++ - 为什么我的函数开始返回 nan?

标签 c++

<分区>

该程序应该运行该函数,直到它满足条件(答案 < 0.01),然后报告该条件所需的服务器数量 (c)。我的程序从来没有达到这一点,因为它在程序中途开始返回 nans。有人可以告诉我我做错了什么吗?

#include <iostream>
#include <cmath>
#include <math.h>


using namespace std;

float product (float p);
float answer;


int main()
{
    cout << "Searching for minimum number of servers..." << endl;

    float c;
    float answer;

    do
    {for (c=1; c<220; c++)
      {
        answer = product(c);
        cout << "when c is " << c << " answer is " << answer << endl;
      }
    }while (answer >= 0.01);

    cout << "when c is " << c << " answer is " << product(c) << endl;
    cout << "Minimum number of servers required is " << c << endl;

    return 0;
}

float product (float p)
{
    float temp;
    float result;
    if (p==0)
        answer = 1;
    else
        temp=200*product(p-1);
        result=temp/(temp+p);
    return result;
}

最佳答案

product 函数中,如果 p 等于 0,则不设置 temp。这会导致 temp 未初始化,并在您稍后计算 result 时包含看似随机的值。

如果您忘记了 else 之后缩进代码周围的大括号,您会保留 result 未初始化,它仍将包含看似随机的值。

这些随机值当然包括NaN

关于c++ - 为什么我的函数开始返回 nan?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15864309/

相关文章:

c++ - 将右值引用传递给 const 左值引用参数

c++ - 类外改变类的值

c++ - Visual Studio 2010 找不到解决方案的局部变量以外的任何定义

没有宏的 C++ 简单反射 : Print Variable Name and Its Value

c++ - 计算文件中字符出现的频率。 C++

c++ - 使用 C++ 附加 CORBA 序列的简单方法

在运行时定义的 C++ 全局 extern 常量可跨多个源文件使用

c++ - 如果 QMenu 是 unique_ptr,为什么 QAction 不添加到 QMenu?

c++ - 如何推断模板中的 C++ 返回类型?

c++ - Cout 不打印号码