C 中的数据类型

发布于 2024-09-12 01:23:17 字数 203 浏览 12 评论 0原文

已知长双精度数使用 80 位。

2^80 = 1208925819614629174706176;

为什么,在声明变量时,例如:

    long double a = 1208925819614629174706175; // 2^80 - 1

我收到一条警告:整数常量对其类型而言太大。

A long double is known to use 80 bits.

2^80 = 1208925819614629174706176;

Why, when declaring a variable such as:

    long double a = 1208925819614629174706175; // 2^80 - 1

I get a warning saying: Integer constant is too large for its type.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

云裳 2024-09-19 01:23:17

1208925819614629174706175 是整数文字,而不是双精度数。你的程序会很乐意转换它,但它必须首先是一个有效的整数。相反,请使用长双精度文字:1208925819614629174706175.0L

1208925819614629174706175 is an integer literal, not a double. Your program would happily convert it, but it would have to be a valid integer first. Instead, use a long double literal: 1208925819614629174706175.0L.

自找没趣 2024-09-19 01:23:17

首先,不知道 long double 类型使用了多少位。这取决于实施。

其次,仅仅因为某些浮点类型使用某些特定数量的位,并不意味着该类型可以使用所有这些位精确地表示整数值(如果这是您想要的)。浮点类型之所以被称为浮点类型,是因为它们表示非整数值,这通常意味着非平凡的内部表示。由于该表示的具体情况,这些位中只有一部分可以用于数字的实际数字。这意味着您的 2^80 - 1 数字将以某种方式被截断/舍入。因此,无论您如何执行此操作,如果编译器警告您数据丢失,请不要感到惊讶。

第三,正如其他答案已经指出的那样,您在程序文本中使用的常量是一个积分常量。对该常量施加的限制与浮点类型完全无关。使用浮点常量而不是整数常量。

Firstly, it is not known how many bits a long double type is using. It depends on the implementation.

Secondly, just because some floating-point type uses some specific number of bits it does not mean that this type can precisely represent an integer value using all these bits (if that's what you want). Floating-point types are called floating-point types because they represent non-integer values, which normally implies a non-trivial internal representation. Due to specifics of that representation, only a portion of these bits can be used for the actual digits of the number. This means that your 2^80 - 1 number will get truncated/rounded in one way or another. So, regardless of how you do it, don't be surprised if the compiler warns you about the data loss.

Thirdly, as other answers have already noted, the constant you are using in the text of your program is an integral constant. The limitations imposed on that constant have nothing to do with floating-point types at all. Use a floating-point constant instead of an integral one.

仲春光 2024-09-19 01:23:17

值 1208925819614629174706175 首先被打包为 const int,然后在赋值时转换为 long double。

The value 1208925819614629174706175 is first crated as a const int, and then converted to a long double, when the assignment happens.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文