简体   繁体   English

C中的“ pow”功能打印的值不正确

[英]Incorrect value printed by the 'pow' function in C

Why does the below code gives 127 as output, when it has to be 128. i have even tried to figure out, but I don't understand why 127? 为什么下面的代码在必须为128时却给出127作为输出。我什至试图弄清楚,但我不明白为什么是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))));

}

If you want 128 as result then typecast pow() result as int instead of char . 如果您希望将128作为结果,则将pow()结果转换为int而不是char for eg 例如

printf("Range is : %u\n", (int)(pow((double)2, (double)(7)))); /* this print 128 */

Why this 为什么这个

printf("Range is : %u\n", (char)(pow((double)2, (double)(7))));

prints 127 as pow((double)2,(double)7) is 128 but at same time that whole result vale explicitly type cast ed as char and default char is signed which ranges from -128 to +127 , hence it prints 127 . pow((double)2,(double)7)128输出127 ,但与此同时整个结果vale 显式地将类型强制转换为charsigned默认char ,范围为-128 to +127 ,因此它输出127

Side note , pow() is floating point function as @lundin suggested & same you can find here . 旁注pow()是@lundin建议的浮点函数,您可以在这里找到。 you can use 您可以使用

unsigned char ch = 1 << 7;

to get the same in particular case. 在特定情况下也一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM