[C++学习]奇怪的除法

重新复习C++,买了本《C++ primer plus》看看。记录一些学习心得。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include<iostream>
using namespace std;

int main()
{

long size_long;

cin >> size_long;
cin.get();

double size_ma = size_long / 0.0; // 0.0算是除数为0了吧?
cout << size_ma << endl;

cin.get();
return 0;
}

然后输出了一个奇怪的数1.#INF
你可能知道,我就不知道,打开浏览器Google!

一个外国博客说:”If your operation would generate a larger positive number than could be stored in a double, the operation will return 1.#INF on Windows or inf on Linux. Similarly your code will return-1.#INF or -inf if the result would be a negative number too large to store in a double.”
意思是说除法计算出来的数太大了,才会返回类似1.#INF,-1.#INF等等。

既然如此,那就好玩了,我们看看Java会不会也是这样!

1
2
3
4
5
6
7
public class Test
{

public static void main(String[] args)
{

System.out.println(111/0.0);
}
}

“正无穷”输出:Infinity “负无穷”输出:-Infinity

果然不出所料。
总结:我们在使用除法时,无论是整数还是小数都要判断除数是否为零的情况,避免出现奇怪的错误(bug)。