用C铸造双打为整数时溢出的处理 [英] Handling overflow when casting doubles to integers in C

查看:106
本文介绍了用C铸造双打为整数时溢出的处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,我注意到,当我投了两倍,比最大可能的整数到整数时,我得到-2147483648。同样,当我投了两倍,小于最小可能的整数,我也得到-2147483648。

Today, I noticed that when I cast a double that is greater than the maximum possible integer to an integer, I get -2147483648. Similarly, when I cast a double that is less than the minimum possible integer, I also get -2147483648.

这是行为的所有平台定义?

什么是检测这种下溢/溢出的最好方法?如果最小和最大INT报表是放投之前的最佳解决方案?

Is this behavior defined for all platforms?
What is the best way to detect this under/overflow? Is putting if statements for min and max int before the cast the best solution?

推荐答案

limits.h中有最大的常量和最小可能值整数数据类型,您可以检查您铸造,像以前一样的双可变

limits.h has constants for max and min possible values for integer data types, you can check your double variable before casting, like

if (my_double > nextafter(INT_MAX, 0) || my_double < nextafter(INT_MIN, 0))
    printf("Overflow!");
else
    my_int = (int)my_double;

编辑:函数nextafter()将解决由nwellnhof

nextafter() will solve the problem mentioned by nwellnhof

这篇关于用C铸造双打为整数时溢出的处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆