I have to write a program that reads length and width from user, calculates and displays area. Also, I need to make separate functions for length, width, area, and display. I do not know how to calculate area.
#include <iostream>
int length;
int width;
int height;
void SetWidth()
{
int temp;
std::cout << "Please enter the width: ";
if(std::cin >> temp)
{
width = temp;
}
else
{
std::cout << "Error while inputting width.\n";
}
}
void SetLength()
{
int temp;
std::cout << "Please enter the length: ";
if(std::cin >> temp)
{
length = temp;
}
else
{
std::cout << "Error while inputting length.\n";
}
}
void GetArea()
{
std::cout << "The area is " << length*width << "\n";
}
int main()
{
GetWidth();
GetLength();
GetArea();
}
EDIT:
Could of easily been a single function. :/
int Area(int l, int w) { return l*w; }
EDIT 2:
The problem is that for this to work you had to declare the variables globally, when you declare them in a function, they are local to the function and nothing but the function can access it ( Unless special things you don't need to worry about just yet )
Just out of curiosity, is this college/university work?
This being probably an assignment and the excessive use of void functions I figured this is how the professor wanted it done ( I have seen a lot of stupid homework questions getting students to do things in such an awful way)
Hi,
if you don't want (in fact, shouldn't) use global var.s, so, why you're using void functions for getWidht() and getLength() functions?!
use double or int type for getLength() and getLength() functions, then in your main functions, define two var.s, like width and length, then assign return value of those functions to them(width = getWidth() and so on... ), and call getArea() function with that parameters.(getArea(width, lengh))
***NOTE: its better to define your functions with lowercase letters(for first letter), and define your classes names with uppercase letters, but its optional.