处理溢出时,将C转换为整数 [英] Handling overflow when casting doubles to integers in C

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

问题描述

今天,我注意到,当我把一个大于最大可能的整数的整数转换为一个整数,我得到-2147483648。类似地,当我投掷小于最小可能整数的double时,我也得到-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.

是否为所有平台定义了此行为?

在/溢出时检测此行为的最佳方法是什么?

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天全站免登陆