为什么在Java中将无穷大转换为字节或短等于-1?

时间:2018-11-20 14:30:18

标签: java type-conversion byte short infinity

最近我发现,如果您使用double或float并将其除以0,则会得到无穷大的值。我将无穷大转换为每种数据类型(通过写import React, { Component } from 'react'; import { BrowserRouter as Router, Route, Link } from 'react-router-dom'; import Login from './components/Login'; import About from './components/About'; import Datas from './components/Datas'; import { Grid, Row, Col } from 'react-bootstrap'; class App extends Component { render() { return ( <Router> <div className="container"> <h1 className="text-center">Todo List App</h1> <Grid> <Row className="show-grid"> <Col xs={6} md={4}> </Col> <Col xs={6} md={4}> <ul className="list-group"> <li className="list-group-item"> <Link to="/login">Login</Link> </li> <li className="list-group-item"> <Link to="/about">About</Link> </li> <li className="list-group-item"> <Link to="/datas">Datas</Link> </li> </ul> </Col> <Col xsHidden md={4}> </Col> </Row> </Grid> <Route exact path="/login" component={Login} /> <Route exact path="/about" component={About} /> <Route exact path="/datas" component={Datas} /> </div> </Router> ); } } export default App; (byte)variable等),我发现如果将其转换为字节或短型,它将得到值-1,但是如果将其转换为任何值其他数据类型则为您提供最大值。我想知道为什么会这样。有人猜到了吗?

这是我用来测试它的代码。

(short)variable

这是控制台给我的:

double dsa = 1.00 / 0;

System.out.println("Byte");
System.out.println((byte)dsa);
System.out.println(Byte.MAX_VALUE + "\n");

System.out.println("Short");
System.out.println((short)dsa);
System.out.println(Short.MAX_VALUE + "\n");

System.out.println("Integer");
System.out.println((int)dsa);
System.out.println(Integer.MAX_VALUE + "\n");

System.out.println("Long");
System.out.println((long)dsa);
System.out.println(Long.MAX_VALUE + "\n");

System.out.println("Float");
System.out.println((float)dsa);
System.out.println(Float.MAX_VALUE + "\n");

System.out.println("Double");
System.out.println((double)dsa);
System.out.println(Double.MAX_VALUE + "\n");

1 个答案:

答案 0 :(得分:-1)

因为正无穷大被定义为0x7ff0000000000000。来自Double类的源代码:

/**
 * A constant holding the positive infinity of type
 * {@code double}. It is equal to the value returned by
 * {@code Double.longBitsToDouble(0x7ff0000000000000L)}.
 */
public static final double POSITIVE_INFINITY = 1.0 / 0.0;

还请注意,广播不是转换