2013-08-31 156 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啊,好吧,我要说你正在使用你从未真正使用过的很多东西。 –