[英]Confusion with simple math in C++
我今天正在玩C ++,這是在做一些測試后發現的:
#include <iostream>
using namespace std;
int main()
{
int myInt = 100;
int myInt2 = myInt + (0.5 * 17); // the math inside the parentheses should go first
int difference = myInt2 - myInt; // get the difference of the two numbers
cout << difference << endl; // difference is 8
}
輸出是8
#include <iostream>
using namespace std;
int main()
{
int myInt = 100;
int myInt2 = myInt - (0.5 * 17); // the math inside the parentheses should still go first
int difference = myInt - myInt2; // get the difference of the two numbers
cout << difference << endl; // difference is 9?
}
輸出是9?
因此,根據我的第一個代碼示例0.5 * 17 = 8,但根據我的第二個代碼示例0.5 * 17 = 9。我在代碼中正在做什么。
為了縮小問題范圍,我嘗試了以下方法:
#include <iostream>
using namespace std;
int main()
{
int myInt = 100;
int myInt2 = 0.5 * 17; // use a variable instead of parentheses
int myInt3 = myInt + myInt2;
int difference = myInt3 - myInt; // get the difference of the two numbers
cout << difference << endl; // difference is 8
}
輸出是8
#include <iostream>
using namespace std;
int main()
{
int myInt = 100;
int myInt2 = 0.5 * 17; // continue using a variable
int myInt3 = myInt - myInt2;
int difference = myInt - myInt3; // get the difference of the two numbers
cout << difference << endl; // difference is 8 again!
}
輸出再次為8!
所以我的問題是,如果括號中的數學始終排在最前面,那為什么我會得到不同的結果? 前兩個試驗的結果不應該與后兩個試驗的結果相同嗎? 我應該提到的另一件事是,我使用其他十進制數字(如0.1和0.3)也得到了相同的結果。
表達式0.5 * 17
結果是浮點值,因為它的成分之一0.5
是浮點。
但是,當您為整數分配一個像8.5
這樣的浮點數時,它將被截斷為8
。 而且,要清楚一點,它在分配時被截斷了。
因此,當您將其分配給整數(a)時,第一個代碼段將計算值100 + 8.5 = 108.5
並將其截斷為108
。 減去100
可得到8
。
在第二個代碼段中,計算值100 - 8.5 = 91.5
然后在分配給整數時將其截斷為91
。 從100
減去得出9
。
最后兩個代碼段起作用的原因是因為8.5
在添加到100
或從100
減去之前在int myInt2 = 0.5 * 17
被更早地截斷了。 在這種情況下, 100 + 8 = 108
和100 - 8 = 92
,兩者與100
的差值恰好為8
(盡管有符號)。
(a)以圖形方式考慮一下可能會有所幫助:
int myInt2 = myInt + (0.5 * 17);
^ int + double * int
| \ \__________/
| \ |
| \ double
| \_____________/
| |
+- truncate <- double
0.5 * 17
,得到浮點8.5
。 myInt = 100
相加, myInt = 100
浮點數108.5
。 myInt2
時將其截斷為108
。 .5 * 17不是8,而是8.5
int myInt = 100;
int myInt2 = myInt + (0.5 * 17);
這將計算100 +(0.5 * 17)或108.5,該值將被截斷為108。
int difference = myInt2 - myInt;
計算得出的結果為108-100,即8。
在第二個示例中:
int myInt = 100;
int myInt2 = myInt - (0.5 * 17);
計算得出的100-8.5或91.5,將被截斷為91。
int difference = myInt - myInt2;
計算得出100-91或9。
您可以用相同的方式來完成其余示例。
您的計算機上有一個非常有用的工具。 它稱為“調試器”。 使用該工具,您可以一次瀏覽一行程序,並在每一步中親自查看所有變量的值。
用整數進行數學運算時,任何小數部分都會在每個步驟中丟失。
因此.5 * 17得出8.5,但存儲在整數變量中的結果為8,該結果將在后續步驟(包括輸出)中使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.