Rectangle Area using functions

Oct 18, 2017 at 11:14pm
There is s silly mistake in my code, i cannot find it for the life of me. As of right now it only returns the area as 0, which i take to mean it isn't receiving the input of length and width? Any help would be greatly appreciated.

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
51
52
53
54
55
56
57
 // Rectangle Area.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
using namespace std;
double getLength(double);
double getWidth(double);
void displayData(double);
double getArea(double, double);


int main()
{
	double area = 0, length = 0, width = 0;	
	 getLength(length);
	 getWidth(width);
	 area = getArea(width, length);
	 displayData(area);
	
	 
	system("pause");
	return 0;
}

double getWidth(double width)
{
	cout << "Please enter the width of your rectangle" << endl;
		cin >> width;
	while (width<0)
	{
		cout << "Error! Please enter a positive number!:" << endl;
		cin >> width;
	}
	return width;
}
double getLength(double length)
{
	cout << "Please enter the length of your rectangle" << endl;
		cin >> length;
	while (length < 0)
	{
		cout << "Error! Please enter a postitive number!" << endl;
	}
	return length;
}
double getArea( double length,double width)
{
	double area = width*length;
	return area;
	
}
void displayData(double area)
{

	cout << "The area of the rectangle is " << area<< endl;
}
Oct 18, 2017 at 11:38pm
You are returning length / width but you aren't assigning it to anything.

1
2
length = getLength(length);
width = getWidth(width);


It looks strange to pass those variables into the functions as well so I would use a temp variable in the functions for that.
Oct 18, 2017 at 11:50pm
Hello MadEye,

Building of what Hippogriff said either use the return value or pass by reference, i.e.,
void getWidth(double& width). This way when you change thee value of "width" or length" in the function it will be changed back in main.

Lines 16 and 17 should look like line 18 unless you pass by reference then no return value is needed and the function call will as you have written it.

Hope that helps,

Andy
Oct 19, 2017 at 12:12am
Thanks so much guys! Can't believe i missed that lol
Topic archived. No new replies allowed.