为什么下面的代码给出 127 作为输出,而它必须是 128。我什至试图弄清楚,但我不明白为什么是 127?
#include<stdio.h>
#include<math.h>
int main()
{
signed char ch;
int size,bits;
size = sizeof(ch);
bits = size * 8;
printf("totals bits is : %d\n",bits);
printf("Range is : %u\n", (char)(pow((double)2, (double)(7))));
}
最佳答案
如果您想要 128
作为结果,请将 pow()
结果类型转换为 int
而不是 char
。例如
printf("Range is : %u\n", (int)(pow((double)2, (double)(7)))); /* this print 128 */
为什么会这样
printf("Range is : %u\n", (char)(pow((double)2, (double)(7))));
打印 127
因为 pow((double)2,(double)7)
是 128
但同时整个结果值 <显式类型转换为 char
,默认 char
为 signed
,范围从 -128 到 +127
,因此它打印 127
。
旁注,pow()
是@lundin建议的浮点函数,您可以找到here 。你可以使用
unsigned char ch = 1 << 7;
在特定情况下得到相同的结果。
关于c - C 中的 'pow' 函数打印的值不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52219436/