该程序应该运行该功能,直到它满足条件(回答< 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;
}
欢迎来到Stack Overflow!要求人们发现代码中的错误并不是特别有效。您应该使用调试器(或者添加打印语句)来分析问题,追踪程序的进度,并将其与预期发生的情况进行比较。只要两者发生分歧,那么你就发现了你的问题。 (然后,如果有必要,你应该构造一个[最小测试用例](http://sscce.org)。) – 2013-04-07 15:49:18
在你的基本情况下(即:'p == 0'),你从不设置'result',你只设置“答案”。我不太熟悉C++标准,但对于某些语言,未初始化的值可能导致未定义的行为。 – 2013-04-07 15:52:23