返回未返回变量值
Return not returning variable value
我为我的类编写了一个练习程序,除了返回变量的值外,它的所有内容都能正常工作。我的问题是,为什么它不返回值?以下是我编写的示例代码,以避免复制和粘贴大部分不相关的代码。
#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
比你实际使用的多?或者这不是完整的代码?
Return
与print
不等价。如果您希望函数返回的值显示在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;
}
相关文章:
- 使用变量值作为 PlaySound 中的路径
- 通过指针偏移量访问结构变量值
- 变量值在 C++ 中的 glutIdleFunc() 中未递增
- 更新 #ifdef 中的现有变量值?
- 尝试更改 main 函数内的全局变量值时出现编译错误 C++.
- 通过 Rcpp 和 bit64 R 包将最大的int64_t变量值从 C++ 传递到 R
- 如何使用 IRBuilder 更新 LLVM IR 中的全局变量值?
- 更改已在运行的程序的变量值
- 在 Xcode 中使用后对外部变量值进行初始化
- C++整数变量值
- 变量值,在三元运算符之后
- 无法赋值,因为函数'operator[]'返回常量值
- 如何获得对不同类的引用,以便从所述类内部获得变量值
- Java应用程序的JNI-c++变量值
- 如何固定从传感器获得的变量值
- 离开方法时重置变量值
- 打印具有通用特定变量值的类对象
- 如何从高性能的输入迭代器返回变体?
- 返回未返回变量值
- 在 if-else 块之外返回变量值