Area and Perimeter of Rectangle in C++
Area and perimeter of a rectangle in C++ from length and width.
1#include <iostream>2using namespace std;34int main() {5 float length, width, area, perimeter;67 cout << "Enter length of rectangle: ";8 cin >> length;910 cout << "Enter width of rectangle: ";11 cin >> width;1213 area = length * width;14 perimeter = 2 * (length + width);1516 cout << "Area of rectangle = " << area << " square units" << endl;17 cout << "Perimeter of rectangle = " << perimeter << " units" << endl;1819 return 0;20}
Output
Enter length of rectangle: 5 Enter width of rectangle: 3 Area of rectangle = 15 square units Perimeter of rectangle = 16 units
What's going on
This C++ program reads length and width, then prints area (length * width) and perimeter (2 * (length + width)).
float length, width, area, perimeter;
float so 5.5 still works. Integers are fine if the problem only uses whole numbers.
cin >> length; then cin >> width;
Sample: 5 and 3.
area = length * width;
5 * 3 = 15.
perimeter = 2 * (length + width);
2 * (5 + 3) = 16. The parentheses matter. 2 * length + width is 13, which is not a perimeter.
Those formulas assume a rectangle: sides meet at right angles. A diagonal is not a width.
Negative length still multiplies. The math runs; the answer is still nonsense. Check < 0 if the input can be bad.
The cout lines label square units vs units. Swap those two prints and the output is confidently wrong.