Program giving wrong output

So I'm just trying to write a program that calculates the area of a rectangle by unnecessarily using functions.

Here's the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
using namespace std;

double getLength (double y);
double getWidth (double x);
double getArea (double x, double y);
double displayData (double x, double y, double area);


int main()

{
	double x;
	double y;
	double area = x * y;
	
	getLength (y);
	getWidth (x);
	getArea (x, y);
	displayData (x, y, area);
	return 0; 	  
}


double getLength (double y)
{
	cout << "What is the length of the rectangle?\n";
	cin >> y;
	return y;
}

double getWidth (double x)
{
	cout << "What is the width of the rectangle?\n";
	cin >> x;
	return x;
}

double getArea (double x, double y)
{
	return x * y;
}

double displayData (double x, double y, double area)
{
	cout << "The rectangle has a length of " << y << ",\n";
	cout <<	"a width of " << x << ",\n";
	cout << "and an area of "<< area << ".\n";
}


Here's the output:

What is the length of the rectangle?
5
What is the width of the rectangle?
6
The rectangle has a length of 1.78843e-307,
a width of 2.26994e+262,
and an area of 4.05962e-45.


Those numbers are far out. I tried initializing x and y at 0. This just returned x, y, and area as equal to 0. What's wrong?
Either pass your parameters by reference and make your get functions return void or use the double's that you are returning.
Dude take it easy on me.

pass your parameters by reference

Huh? How? What does that mean?

use the double's that you are returning

Where?
The tutorial available on this website http://www.cplusplus.com/doc/tutorial/ will remedy the issues you are encountering.

double getLength(double y);

To pass y by reference you should change the prototype / implementation to reflect this (note the addition of the & operator ):

double getLength(double & y);

But based on how you are using the code passing by reference nullifies the need for the return type "double" so it should logically be changed to this

void getLength(double & y);

My other suggestion was to use the double's you are returning.

In your getLength() function you return y at the end of it. If you look inside your main function there is no variable there to recieve the return value.

If you want to store that double value there needs to be something there to get assigned that value. You could change the code in main to reflect that by doing something like

1
2
3
double length; // declared somewhere in main
...
length = getLength();


In this case no parameter needs to be passed to getLength, so your function prototype should be

double getLength();

If this is above your head I urge you to read some more.

Good luck.
Last edited on
Topic archived. No new replies allowed.