C++ gcc 大量错误

C++ gcc large number errors

我的 C++ 项目需要处理行星质量数...最多超过 24 位数字。他们是花车。相同的变量也可能是一个相对较小的数字(100)我尝试使用双精度和长精度,但是在 linux 中使用 G++ 进行编译我收到警告:警告:

整数常量与其类型相比太大[默认启用]。

我的计算也因此不起作用。我想知道这种数字需要什么类型的变量。

我做了研究,但结果很枯燥..不过,如果这个问题经常出现,我深表歉意。谢谢!

如果你有这样一段代码:

double mass = 31415926535892718281828459;

那么你需要明白常量是一个整数。整个语句会在将其放入 mass 之前将其变成 double 但您的方案在 之前 失败。

您需要直接告诉编译器它是一个双精度值,例如:

double mass = 31415926535892718281828459.0;

C++11 的第 2.14 节详细介绍了文字及其定义方式。一组数字,其中第一个不是 0,由 2.14.2 Integer literals 部分的以下规则捕获:

decimal-literal:
    nonzero-digit
    decimal-literal digit

(以0开头的一组数字仍然是整数,只是由八进制数字而不是十进制数字组成)。

部分 2.14.4 Floating literals 展示了如何指示编译器您想要 double 例如:

  • 包括 1.41415. 中的小数部分;或
  • 使用 12e2 中的指数表示法。

或者,对于那里的语言律师:

A floating literal consists of an integer part, a decimal point, a fraction part, an e or E, an optionally signed integer exponent, and an optional type suffix. The integer and fraction parts both consist of a sequence of decimal (base ten) digits. Either the integer part or the fraction part (not both) can be omitted; either the decimal point or the letter e (or E) and the exponent (not both) can be omitted.

The type of a floating literal is double unless explicitly specified by a suffix. The suffixes f and F specify float, the suffixes l and L specify long double.

您需要确保它是双倍的:

123456789012345678   // integer, give warning
123456789012345678.0 // double (floating point)

如果您需要更高的精度,您应该考虑使用大数库。另见 C++ library for big float numbers

这是一个产生此警告的简单测试用例:

float foo() {
  return 1000000000000000000000000;
}

问题是那里写的数字实际上是一个整数文字。这段代码基本上是说 "take this value as an int, convert it to float, and return that." 但是这个数字太大而不适合 int.

解决方案:在数字末尾添加“.0”或“.0f”,使其成为 doublefloat 文字而不是 int