函数不返回值,但 cout 显示它
Function not returning value, but cout displays it
我已经学习了一段时间C++,并尝试制作一个简单的函数来返回房间的面积。return 语句不输出值,但是使用 cout 我可以看到结果。我在这里错过了什么吗?
#include <iostream>
using namespace std;
int Area(int x, int y);
int main()
{
int len;
int wid;
int area;
cout << "Hello, enter the length and width of your room." << endl;
cin >> len >> wid;
cout << "The area of your room is: ";
Area(len, wid);
return 0;
}
int Area(int len, int wid)
{
int answer = ( len * wid );
return answer;
}
std::cout
用于在屏幕上打印数据。函数仅返回值,因此Area
函数将返回要在函数中传递的值std::ostream::operator<<
以打印它。你需要写:
std::cout << Area(len, wid) << "n";
return
不会打印任何内容,您不应该期望它打印。它所做的只是从函数返回一个值。然后,您可以对该值执行任何操作,包括打印它或将其分配给变量:
// Does not print:
Area(len, wid);
// Does print:
int result = Area(len, wid);
std::cout << result << "n";
// Does print:
std::cout << Area(len, wid) << "n";
想象一下,如果一个庞大的代码库中的每个函数突然开始打印其返回值,那会有多混乱......
相关文章:
- 如何在C++中用std::cout正确显示带十六进制的字符串文本
- 为什么在C的循环中使用printf的Rust代码不显示输出,而在C++的循环中显示std::cout
- 为什么我的 cout 在输出中没有显示字符串?
- 为什么strlen(s)与s的大小不同,为什么cout-char显示的是字符而不是数字
- 使用 CIN COUT 显示垃圾值的文件对象?
- 'cout'将整数显示为十六进制
- 如何使用 cout 显示类中类的值?
- 函数不返回值,但 cout 显示它
- C 未显示COUT信息
- printf 整数显示超过 C++ cout
- 为什么当我使用 cout 显示输出时,必须将按位运算符(例如 &,|,等)括在括号中?
- Jupyter笔记本未显示C 输出(COUT)
- 为什么我的 C++ 代码不能显示 cout 字符串
- 将字符串添加到2D数组并显示COUT消息(没有错误消息?)的错误
- C++ - 为什么我的cout代码显示小数不一致
- 为什么 cout 不显示字符串变量 rnd
- 返回前的 cout 显示的数字与主数字大不相同
- 当我调用std::abort()时,cout没有显示
- Xcode调试器未显示C++cout输出
- 用cout显示双精度的c++问题