Math errors in a basic C ++ program

I am working with a basic C ++ program to determine the area and perimeter of a rectangle. My program works fine for integers, but it falls apart when I use any number with a decimal point. I get the impression that I'm leaving something, but since I'm a complete beginner, I have no idea what.

Below is the source:

#include <iostream> using namespace std; int main() { // Declared variables int length; // declares variable for length int width; // declares variable for width int area; // declares variable for area int perimeter; // declares variable for perimeter // Statements cout << "Enter the length and the width of the rectangle: "; // states what information to enter cin >> length >> width; // user input of length and width cout << endl; // closes the input area = length * width; // calculates area of rectangle perimeter = 2 * (length + width); //calculates perimeter of rectangle cout << "The area of the rectangle = " << area << " square units." <<endl; // displays the calculation of the area cout << "The perimeter of the rectangle = " << perimeter << " units." << endl; // displays the calculation of the perimeter system ("pause"); // REMOVE BEFORE RELEASE - testing purposes only return 0; } 
+4
source share
5 answers

Change all variables of type int to double or float . I personally would use double , because they have more precision than float types .

+2
source

int datatype means an integer (i.e. positive and negative integers, including 0)

If you want to represent decimal numbers, you will need to use float.

+2
source

Use a float or double type, like the others already mentioned.

But it is not so simple. You need to understand what floating point numbers are and why (0.1 + 0.1 + 0.1)! = (0.3). This is a difficult question, so I won’t even try to explain it here - just remember that the float is not decimal, even if the computer displays it to you as decimal.

+2
source

use float not ints integer (int) - an integer, float allows decimal places (like doubles)

 float length; // declares variable for length float width; // declares variable for width float area; // declares variable for area float perimeter; // declares variable for perimete 
0
source

You defined the variables as integers. Use double instead.

In addition, you can find some formatting for cout to determine the number of decimal places you want to show, etc.

0
source

Source: https://habr.com/ru/post/1312715/


All Articles