2013-08-31 155 views
5

我爲我的課寫了一個練習程序,除了返回變量的值之外,其中的所有內容都有效。我的問題是,爲什麼它沒有返回值?以下是我寫出的示例代碼,以避免複製和粘貼大部分不相關的代碼。返回不返回變量值

#include <iostream> 
using std::cout; using std::cin; 
using std::endl; using std::fixed; 

#include <iomanip> 
using std::setw; using std::setprecision; 

int testing(); 

int main() 
{ 
    testing(); 

    return 0; 

} 

int testing() { 
    int debtArray[] = {4,5,6,7,9,}; 
    int total = 0; 

    for(int debt = 0; debt < 5; debt++) { 
    total += debtArray[debt]; 
    } 

    return total; 
} 
+2

該代碼只是丟棄返回值。嘗試將'testing();'更改爲'std :: cout << testing();'看看你是否沒有得到什麼。 –

+1

'testing'函數的確會返回一個值。但是你只是在通話中放棄了這個價值。你期望會發生什麼? –

+1

*「以下是我爲避免複製和粘貼大部分不相關的代碼而寫出的示例代碼。」* - 我們非常感謝您的支持。 –

回答

9

事實上,功能返回一個值。但是,main()正在選擇忽略該返回值。

嘗試在你的main()如下:

int total = testing(); 
std::cout << "The total is " << total << std::endl; 
2

你的代碼是完美的,但它並不需要正在由功能testing() 返回的值試試這個,
這將認爲是作爲數據由您的testing()函數返回

#include <iostream> 
using std::cout; using std::cin; 
using std::endl; using std::fixed; 

#include <iomanip> 
using std::setw; using std::setprecision; 

int testing(); 

int main() 
{ 
    int res = testing(); 
    cout<<"calling of testing() returned : \t"<<res<<"\n"; 
    return 0; 

} 

int testing() { 
    int debtArray[] = {4,5,6,7,9,}; 
    int total = 0; 

    for(int debt = 0; debt < 5; debt++) { 
    total += debtArray[debt]; 
    } 

    return total; 
} 
4

該函數確實會返回一個值。 您沒有在屏幕上顯示返回值,因此您認爲它不會返回值的原因

3

Return不等於print。如果你想要函數返回的值顯示到標準輸出,你必須有一個方法來做到這一點。這是由印刷無論是在主或功能使用std::cout返回的值和<<運營商實現自身

4

testing()確實返回一個值,但該值不習慣或任何保存。你是using std :: cout,std :: cin,std :: endl等,但你不是他們使用他們。我假設你想要做的是顯示total。一種是程序看起來像:

#include <iostream> 
using std::cout; 
using std::endl; 

int testing(); 

int main() { 
    int totaldebt = testing(); 
    cout << totaldebt << endl; 

    return 0; 
} 

int testing() { 
    int debtArray[] = {4,5,6,7,9}; 
    int total = 0; 

    for(int debt = 0; debt < 5; debt++) { 
     total += debtArray[debt]; 
    } 

    return total; 
} 

什麼是你的代碼中發生的(假設編譯器以任何方式不優化)內main()testing()被調用時,經過其指令,然後程序繼續前進。如果您從<cstdlib>撥打printf,也會發生同樣的情況。 printf應該返回它顯示的字符數量,但如果不在任何地方存儲結果,它只會顯示文本並繼續執行程序。

我不得不問的是爲什麼你using超過你實際使用?或者這不是完整的代碼?

+0

不是完整的代碼。 – ExpletiveDeleted

+0

@ExpletiveDeleted啊,好吧,我要說你正在使用你從未真正使用過的很多東西。 –