2013-04-07 39 views
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; 
} 
+7

歡迎來到Stack Overflow!要求人們發現代碼中的錯誤並不是特別有效。您應該使用調試器(或者添加打印語句)來分析問題,追蹤程序的進度,並將其與預期發生的情況進行比較。只要兩者發生分歧,那麼你就發現了你的問題。 (然後,如果有必要,你應該構造一個[最小測試用例](http://sscce.org)。) – 2013-04-07 15:49:18

+0

在你的基本情況下(即:'p == 0'),你從不設置'result',你只設置「答案」。我不太熟悉C++標準,但對於某些語言,未初始化的值可能導致未定義的行爲。 – 2013-04-07 15:52:23

回答

1

product功能,您沒有設置temp如果p等於0。這會導致temp未初始化,並且在稍後計算result時會包含看似隨機的值。

如果您在else之後忘記了縮進代碼的大括號,那麼您會將result保留爲未初始化狀態,並且它仍將包含看似隨機的值。

這些隨機值當然包括NaN

+0

謝謝你的幫助! – AS10999 2013-04-07 22:57:40

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條件。

0
  1. 其他

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

  2. if(p == 0) result = 1 後添加兩個語句周圍括號分配答案= 1,然後返回結果,這是在這種情況下,未初始化會給你的NaN值當p = 0.儘管在當前情況下p永遠不會爲零,因爲參數c傳遞給product的範圍介於1和220之間。

  3. 刪除全局變量的聲明answer。最有可能的是,你不需要它。

相關問題