函数不返回值,但 cout 显示它

Function not returning value, but cout displays it

本文关键字:cout 显示 返回值 函数      更新时间:2023-10-16

我已经学习了一段时间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";

想象一下,如果一个庞大的代码库中的每个函数突然开始打印其返回值,那会有多混乱......