与c++中的简单数学混淆

Confusion with simple math in C++

本文关键字:简单 c++      更新时间:2023-10-16

我今天在玩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。而且,为了说明这一点,它在赋值点被截断。

因此,第一个代码段计算值100 + 8.5 = 108.5,并在将其赋值给整数(a)时将其截断为108。再减去100,就得到8

在第二个代码段中,计算值100 - 8.5 = 91.5,并在赋值给整型时将其截断为91。从100中减去它得到9

最后两个代码段工作的原因是8.5int myInt2 = 0.5 * 17中之前被截断100中被添加或减去之前。在这种情况下,100 + 8 = 108100 - 8 = 92,它们都与100不同,正好是8(尽管有符号)。


(a)这可能有助于图形化思考:

int myInt2 = myInt + (0.5    * 17);
       ^     int   +  double * int
       |             __________/
       |                  |
       |                double
       |        _____________/
       |                |
       +- truncate <- double
  • 首先计算0.5 * 17,得到浮点数8.5
  • 然后将其与整数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。

以同样的方式,你可以完成剩下的例子。

你的电脑上有一个非常有用的工具。它被称为"调试器"。使用这个工具,您可以一步一步地遍历任何程序,每次一行,并在每一步中亲自查看所有变量的值。

当用整数做数学运算时,每一步都会丢失任何小数部分。

因此,0.5 * 17得到8.5,但是存储在整数变量中的结果是8,它将在后续步骤中使用,包括输出。