C++ 中 double 类型 0 和 –0 的运算

C++ 的 double 是有负零(negative zero)的。负零在某些计算中是有意义的。例如:

1.0/0.0 == INFINITY
1.0/-0.0 == –INFINITY

 

除此之外,负零在某些数学函数中也有利用,例如 sqrt(std::complex)

同时零和负零的加减计算也有它的特殊性,例如下面的代码:

#include <iostream>
int main()
{
	double a(1.0), b(0.0), c(-0.0);
	std::cout << std::hex;
	std::cout << "a = " << a << std::endl;
	std::cout << "b = " << b << std::endl;
	std::cout << "c = " << c << std::endl;

	std::cout << "作为除数" << std::endl;
	std::cout << a << " / " << b << " = " << a / b << std::endl;
	std::cout << a << " / " << c << " = " << a / c << std::endl;

	std::cout << "加法" << std::endl;
	std::cout << a << " + " << c << " = " << a + c << std::endl;
	std::cout << b << " + " << c  << " = " << b + c << std::endl;
	std::cout << c << " + " << c << " = " << c + c << std::endl;

	std::cout << "减法" << std::endl;
	std::cout << a << " - " << c << " = " << a - c << std::endl;
	std::cout << b << " - " << c << " = " << b - c << std::endl;
	std::cout << c << " - " << b << " = " << c - b << std::endl;
	std::cout << c << " - " << c << " = " << c - c << std::endl;
	
	std::cout << "乘法" << std::endl;
	std::cout << a << " * " << c << " = " << a * c << std::endl;
	std::cout << b << " * " << c << " = " << b * c << std::endl;
	std::cout << c << " * " << c << " = " << c * c << std::endl;

	std::cout << "除法" << std::endl;
	std::cout << b << " / " << b << " = " << b / b << std::endl;
	std::cout << b << " / " << c << " = " << b / c << std::endl;
    return 0;
}

这段代码在 VS2015 中编译运行的结果为:

428

从结果中可以看出零和负零的各种运算结果。

posted @ 2016-04-28 22:59  钉钉铛铛  阅读(5180)  评论(0编辑  收藏  举报