返回未返回变量值

Return not returning variable value

本文关键字:返回 变量值      更新时间:2023-10-16

我为我的类编写了一个练习程序,除了返回变量的值外,它的所有内容都能正常工作。我的问题是,为什么它不返回值?以下是我编写的示例代码,以避免复制和粘贴大部分不相关的代码。

#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;
}

实际上,函数正在返回一个值。但是,main()选择忽略该返回值。

main():中尝试以下操作

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

函数确实返回了一个值。您没有在屏幕上显示返回的值,因此您认为它不会返回值

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比你实际使用的多?或者这不是完整的代码?

Returnprint不等价。如果您希望函数返回的值显示在stdout中,则必须有一种方法。这是通过打印使用std::cout<<运算符返回的值来实现的,无论是在main中还是在函数本身

您的代码是完美的,但它不接受函数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;
}