背景
在 【C++ 程序】 牛顿迭代法求一元二次方程的解(包括复数解)中,本来会有输出-0
的情况,如下图:
为什么会输出-0
呢?我进行了一些思考。
试验程序
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
int a1 = 0, b1 = 1;
int A1 = -0, B1 = -1;
double a2 = 0, b2 = 1;
double A2 = -0, B2 = -1;
cout << "a1,A1 = " << a1 << "," << A1 << endl;
cout << "a2,A2 = " << a2 << "," << A2 << endl;
if (a1 == A1) cout << "a1 == A1" << endl;
else cout << "a1 != A1" << endl;
if (a2 == A2) cout << "a2 == A2" << endl;
else cout << "a2 != A2" << endl;
cout << "a1/b1 = " << a1 / b1 << endl;
cout << "A1/B1 = " << A1 / B1 << endl;
cout << "a2/b2 = " << a2 / b2 << endl;
cout << "A2/B2 = " << A2 / B2 << endl;
cout << "A2/b2 = " << A2 / b2 << endl;
cout << "a2/B2 = " << a2 / B2 << endl;
cout << "The address of a2 is " << &a2 << endl;
cout << "The address of A2 is " << &A2 << endl;
double result1 = A2 / B2;
double result2 = A2 / b2;
cout << "The address of result1 is " << &result1 << endl;
cout << "The address of result2 is " << &result2 << endl;
return 0;
}
并在第28行设置断点,调试(F5),查看内存(Memory):
(中文界面路径:调试->窗口->内存)
在 Address 中输入地址即可看到其内存(这是16进制下的内存表示),发现-0
的表示果然就是第一位1,后面全是0。不过在判断中,-0
和0
相等。
在输出时,-0
和0
是不一样的。
关于编码,详见我的博客 【SEU程序设计课笔记】 04 - 2020/10/19 - Numbers in the computer - 进制/编码/孪生素数/sin(x)的泰勒展开中的编码部分。
(这里可以修改查看的方式)
总结
-0
和0
计算上基本无区别,但实际上在存储时的二进制代码是不一样的。这都和二进制运算有关。(电脑不会计算,只是某些操作恰好符合了运算规律)
ALL RIGHTS RESERVED © 2020 Teddy van Jerry
欢迎转载,转载请注明出处。