Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
499 views
in Technique[技术] by (71.8m points)

c++ - Function not returning value, but cout displays it

I've been learning C++ for a bit and tried my hand at making a simple function that returns the area of a room. The return statement doesn't output the value, however using cout I can see the result. Am I missing something here?

#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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

std::cout is used to print data on screen. Functions only return values, so the Area function will return the value which is to be passed in std::ostream::operator<< function to print it. You need to write:

std::cout << Area(len, wid) << "
";

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...