該程序應該運行該功能,直到它滿足條件(回答< 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