长类型Max等于int Max error + math.h pow()编译警告:隐式常量转换溢出

long type max equaling int max error + math.h pow() compile warning: overflow in implicit constant conversion

本文关键字:Max 警告 编译 常量 溢出 转换 pow int 等于 类型 error      更新时间:2023-10-16

我正在使用math.h库,当我运行下面的代码时,我得到g++编译错误告诉我多行"警告:隐式常量转换溢出"。但是,如果我运行可执行文件,它会为我提供合理的数字(尽管由于某种原因,int和long的最大值返回相同的值)。但如果我使用cmath库,所有带符号数据类型都给我负值,无符号数据类型都返回0....

c++:

/* Calculating data type sizes directly */
/* Shorts - 2 bytes = 2*8(bits/byte) = 16 bits */
smallest_short = -(pow(2, 15));
largest_short = pow(2,15);               // LINE 141
us_smallest_short = 0;
us_largest_short = pow(2, 16);             // LINE 143
/* Ints - 4 bytes = 4*8(bits/byte) = 32 bits */
smallest_int = -(pow(2, 31));
largest_int = pow(2, 31);                  // LINE 147
us_smallest_int = 0
us_largest_int = pow(2, 32);                 // LINE 149
/* Long - 8 bytes = 8*8(bits/byte) = 64 bits */
smallest_long = -(pow(2, 63));
largest_long = pow(2, 63);                 // LINE 153
us_smallest_long = 0;
us_largest_long = pow(2, 64);                   // LINE 155

c++编译错误:

datatypesexp.cpp: In function âint main()â:
datatypesexp.cpp:141: warning: overflow in implicit constant conversion
datatypesexp.cpp:143: warning: overflow in implicit constant conversion
datatypesexp.cpp:147: warning: overflow in implicit constant conversion
datatypesexp.cpp:149: warning: overflow in implicit constant conversion
datatypesexp.cpp:153: warning: overflow in implicit constant conversion
datatypesexp.cpp:155: warning: overflow in implicit constant conversion

我应该坚持使用math.h吗?如何解决警告?

,如果我用math.h运行exec,忽略警告,我的带符号的"最大int"answers"最大long"都返回2147483647。

当无符号时,它们都返回4294967295。但是long应该返回一个更大的值…

我该如何补救?

正值溢出,因为在刻度的那一边有一个0要容纳,使您少了一个值。例如,pow(2, 31)是2,147,483,648(赋值前表示为双精度),但在这种情况下,最大的有符号整数是2,147,483,647。

无符号n位变量能保存的最大值是2^n-1,而不是2^n。