0

该程序应该运行该函数,直到它满足条件(答案 < 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;
}
4

3 回答 3

1

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

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

这些随机值当然包括NaN.

于 2013-04-07T15:53:10.900 回答
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;
}

请注意,我添加了{}周围的else条件。

于 2013-04-07T15:54:25.840 回答
0
  1. 在 else 之后在两个语句周围添加大括号

    else { temp=200*product(p-1); result=temp/(temp+p); }

  2. if(p == 0) result = 1 分配 answer = 1 然后返回结果,在这种情况下未初始化的结果将在 p = 0 时为您提供 NaN 值。尽管在当前情况下 p 永远不会为零,因为c传递的参数product范围在 1 到 220 之间。

  3. 删除全局变量的声明answer。很可能,您不需要它。

于 2013-04-07T16:17:17.763 回答