科学记数法对C中的整数常量安全吗? [英] Is scientific notation safe for integer constants in C?

查看:99
本文介绍了科学记数法对C中的整数常量安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一段时间以来,我一直在使用科学计数法表示常数的10的大幂,只是这样,我不必计算零.例如

For a while, I've been representing large powers of 10 in constants using scientific notation, just so I don't have to count the zeros. e.g.

#define DELAY_USEC 1e6

一位同事指出,这是不安全的,因为它不是整数,并且不能保证始终等于1000000.文档似乎证实了这一点,但是我想知道它是否在实际中是正确的.有什么方法可以使用速记方式安全地声明一个十进制的整数?将其强制转换为定义中的int是否安全?

A colleague pointed out that this isn't safe, because it's not an integer and is not guaranteed to always equal 1000000 exactly. Documentation seems to confirm this, but I'm wondering if its true in practicality. Is there any way to safely declare a power-of-ten integer using a shorthand? Is it safe just to cast it to an int in the define?

推荐答案

从理论上讲,没有.两种语言都没有指定浮点值的表示方式或可以准确表示哪些值. (更新:显然,C11确实推荐一种表示形式.C++和较旧的C语言则不这样做.)

In theory, no. Neither language specifies how floating point values are represented, or which values can be represented exactly. (UPDATE: apparently, C11 does recommend a representation. C++, and older C dialects, don't).

实际上,是的,对于很大范围的值.您很可能会遇到的任何实现都将对double使用 64位IEEE表示形式.它可以精确地表示最大为2 53 (大约9x10 15 )的任何整数值.它肯定可以代表32位整数类型可以表示的任何内容.

In practice, yes, for quite a large range of values. Any implementation you're remotely likely to encounter will use a 64-bit IEEE representation for double. This can represent any integer value up to 253 (approximately 9x1015) exactly. It can certainly represent anything representable by a 32-bit integer type.

这篇关于科学记数法对C中的整数常量安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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