[英]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";
想象一下,如果龐大的代碼庫中的每個函數突然開始打印其返回值,那么混亂......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.