[英]Mathematics errors in basic C++ program
我正在使用基本的C ++程序來確定矩形的面積和周長。 我的程序適用於整數,但當我使用帶小數的任何數字時會崩潰。 我得到的印象是我要留下一些東西,但由於我是一個完全的初學者,我不知道是什么。
以下是來源:
#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;
}
將所有int
類型變量更改為double
或float
。 我個人會使用double
因為它們比float types
更精確。
int數據類型代表整數(即正整數和負整數,包括0)
如果要表示十進制數,則需要使用float。
使用float或double類型,就像其他已經說過的那樣。
但它並不那么簡單。 您需要了解浮點數實際上是什么,以及為什么(0.1 + 0.1 + 0.1)!=(0.3)。 這是一個復雜的主題,所以我甚至不會在這里解釋它 - 只要記住浮點數不是小數,即使計算機以小數形式顯示給你。
使用浮點數不是整數(int)是一個整數,浮點數允許小數位(如同雙精度數)
float length; // declares variable for length
float width; // declares variable for width
float area; // declares variable for area
float perimeter; // declares variable for perimete
您已將變量定義為整數。 請改用雙。
此外,您可以查找cout的一些格式以定義要顯示的小數位數等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.