2012-02-18 90 views
0

好的我在這裏爲我的學校計劃感到有點困惑。該程序執行,我得到了我想要的結果,但我只是覺得可能會更好。在我的findLowest()函數中它有一個int返回。那麼我在參數中傳入的數據類型是double。具有一個返回類型的函數可以具有不同的數據類型參數嗎?或者我應該說有沒有更好的方法來做到這一點,也許是鑄造?我沒有問題,但找到最低需要調用calcAverage(),這讓我難倒,因爲如果我改變了數據成員比顯然正確的數據不會傳遞到每個函數和傳遞。這裏是程序中的代碼片斷,感謝任何想法提前,如果需要它可以始終保持原樣,它的工作原理。函數中返回值的數據類型不同?

//function averages input test scores 
void calcAverage(double score1, double score2, double score3, double score4, double score5) 
{ 
    //call to findLowest() function to decide which score to omit 

     double lowest = findLowest(score1, score2, score3, score4, score5); 

     double average = ((score1 + score2 + score3 + score4 + score5) - lowest)/4; 

     cout << "Average is: " << average << endl; 

} 

//determines which input score is lowest 
int findLowest(double score1, double score2, double score3, double score4, double score5) 
{ 

    double low = score1;  

    if(score2 < low) 
     low = score2; 
    if(score3 < low) 
      low = score3; 
    if(score4 < low) 
     low = score4; 
    if(score5 < low) 
     low = score5; 

    cout << "Lowest score is: " << low << endl; 


return low; 
} 
+0

你有沒有學過數組/矢量呢?得分1,得分2等將很快達到理智的限度。 – Duck 2012-02-18 23:33:38

+0

@Duck我希望我可以使用他們,但他們是下一章,我不允許使用他們 – Gmenfan83 2012-02-18 23:34:24

回答

2

爲什麼不改變findLowest的返回類型加倍?

2

findLowest函數體定義double low但是你回到它作爲int,這樣就可以再次把它分配給double

將此返回值的類型從int更改爲double,一切都會好起來的。

「一個返回類型的函數可以具有不同的數據類型參數嗎?」
當然可以。返回值的類型不一定與參數的類型有關。

「問題是在聲明它說,使用功能int findLowest問題書」
這本書也許作者想要你做這樣的事情:

#include <limits> 
#include <vector> 
... 
int findLowest(vector<double>& v) 
{ 
    int lowest = -1; 
    double lowestValue = numeric_limits<double>::max(); 
    for (int i = 0; i < v.size(); ++i) 
    { 
     if (v[i] < lowestValue) 
     { 
      lowestValue = v[i]; 
      lowest = i; 
     } 
    } 
    cout << "Lowest score is: " << lowestValue << " at index: " << lowest << endl; 
    return lowest; 
} 
... 
    // in calcAverage: 
    vector<double> args; 
    args.resize(5); 
    args[0] = score1; args[1] = score2; args[2] = score3; args[3] = score4; args[4] = score5; 

    int lowest = findLowest(args); 
    args[lowest] = 0; 
    double average = (args[0] + args[1] + args[2] + args[3] + args[4])/4; 
+0

這就是我所困惑的和我的懷疑是正確的,因此我的問題。問題出現在書中,它指出了它對我們說函數int findLowest的問題。因此我不確定它可以改變。問題是它有點被改變,因爲我正在處理雙打而不是整數 – Gmenfan83 2012-02-18 23:33:15

+1

@ Gmenfan83施法不會幫助你。即使您在函數內部投射,但返回一個int,它也會返回一個「int」,所以除非您更改返回類型,否則可能會丟失數據。 – Sid 2012-02-18 23:35:20

+0

@ Gmenfan83:現在查看我的答案。現在顯示可能的解決方案。 – LihO 2012-02-19 00:02:53

1

當然,你可以。您可以通過foo類型並返回bar類型。

在你的例子中,你需要知道一件事。當您將double的值分配給int類型時,可以截斷它們。所以你失去了精確度。如果你通過0.254,你可能會得到0。這可能不是被調用者期望的。

我會改變findLowest,這樣它會返回一個double,最好儘可能地堅持正確的類型。

根據要求,更好的解決方案可能是返回一個int,表示五個數字中的哪一個較低。所以如果你打電話給findLowest(2.3, 4, 0, 9, 6)它會返回2. findLowest(1, 2, 3, 4, 5) = 0

+0

)我只是把回報改成了兩倍,我相信我的教授在處理雙打時可以理解,而不是懲罰我。爲了嘗試把事情搞清楚! – Gmenfan83 2012-02-19 00:20:05

相關問題