c - C 中的 'pow' 函数打印的值不正确

标签 c

为什么下面的代码给出 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,默认 charsigned,范围从 -128 到 +127 ,因此它打印 127

旁注pow()是@lundin建议的浮点函数,您可以找到here 。你可以使用

unsigned char ch = 1 << 7;

在特定情况下得到相同的结果。

关于c - C 中的 'pow' 函数打印的值不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52219436/

相关文章:

c - "__aeabi_ldivmod"编译内核模块时未定义

c - 为什么 a[6] 显示 344 值

c - 如何使用用户输入的结构填充动态数组的元素?

php - PHP 与 C 中的增量哈希

初学者的 cstring 麻烦

c - 共享库 (PIC) 返回指向调用者结果的指针 SEGFAULT

C++ 如何将整数和长整型转换为 char 数组

c - 使用文件描述符在 C 中读取文件

c++ - stat() 函数未正确返回

c - 如何将 char 数组作为参数传递给 C 中的函数?