简体   繁体   English

如果我将一个double转换为int会发生什么,但double的值超出范围?

[英]What happens if I cast a double to an int, but the value of the double is out of range?

What happens if I cast a double to an int, but the value of the double is out of range? 如果我将一个double转换为int会发生什么,但double的值超出范围?

Lets say I do something like this? 让我说我做这样的事情?

double d = double(INT_MIN) - 10000.0;
int a = (int)d;

What is the value of a? 什么是a的价值? Is it undefined? 这是不确定的?

Precisely. 正是。 Quoting from the Standard, 4.9, "The behavior is undefined if the truncated value cannot be represented in the destination type." 引用标准4.9,“如果截断值无法在目标类型中表示,则行为未定义。”

David Thornley answered this question completely already. David Thornley已经完全回答了这个问题。 However to deal with this situation in your code you should consider boost's numeric_cast . 但是要在代码中处理这种情况,你应该考虑使用boost的numeric_cast

double d = double(INT_MIN) - 10000.0;
int a = boost::numeric_cast<int>(d);

This will throw an exception at runtime if d is too big for an int . 如果d对于int来说太大,这将在运行时抛出异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM