减去十六进制
Subtracting Hexadecimals
当我将一个变量声明为 float 并减去两个十六进制数时,我每次编译和 运行 时都会得到不同的答案。如果我声明一个整数变量,每次编译和 运行 代码时结果都保持不变。我不明白为什么每次使用相同的两个数字 (0xFF0000 - 0xFF7FF)
进行编译时,将结果存储在浮点数中都会发生变化
int main()
{
float BlocksLeft = 0xFF0000 - 0xFF7FF;
int BLeft = 0xFF0000 - 0xFF7FF;
printf("%08x\n", BlocksLeft);
printf("%08x\n", BLeft);
}
下面这行是不正确的:
printf("%08x\n", BlocksLeft);
%x
格式将指示编译器您提供的参数是一个 int。这会导致未定义的行为。我试图编译你的代码,我得到:
>gcc -Wall -Wextra -Werror -std=gnu99 -o Whosebug.exe Whosebug.c
Whosebug.c: In function 'main':
Whosebug.c:15:4: error: format '%x' expects argument of type 'unsigned int', but argument 2 has type 'double' [-Werror=format=]
printf("%08x\n", BlocksLeft);
^
请尝试使用更强的警告级别进行编译,至少 -Wall
。
您可以这样修正您的程序,例如:
#include <stdio.h>
int main()
{
float BlocksLeft = 0xFF0000 - 0xFF7FF;
int BLeft = 0xFF0000 - 0xFF7FF;
printf("%08x\n", (int) BlocksLeft); // Works because BlocksLeft's value is non negative
// or
printf("%08x\n", (unsigned int) BlocksLeft);
// or
printf("%.8e\n", BlocksLeft);
printf("%08x\n", BLeft);
}
当我将一个变量声明为 float 并减去两个十六进制数时,我每次编译和 运行 时都会得到不同的答案。如果我声明一个整数变量,每次编译和 运行 代码时结果都保持不变。我不明白为什么每次使用相同的两个数字 (0xFF0000 - 0xFF7FF)
进行编译时,将结果存储在浮点数中都会发生变化int main()
{
float BlocksLeft = 0xFF0000 - 0xFF7FF;
int BLeft = 0xFF0000 - 0xFF7FF;
printf("%08x\n", BlocksLeft);
printf("%08x\n", BLeft);
}
下面这行是不正确的:
printf("%08x\n", BlocksLeft);
%x
格式将指示编译器您提供的参数是一个 int。这会导致未定义的行为。我试图编译你的代码,我得到:
>gcc -Wall -Wextra -Werror -std=gnu99 -o Whosebug.exe Whosebug.c
Whosebug.c: In function 'main':
Whosebug.c:15:4: error: format '%x' expects argument of type 'unsigned int', but argument 2 has type 'double' [-Werror=format=]
printf("%08x\n", BlocksLeft);
^
请尝试使用更强的警告级别进行编译,至少 -Wall
。
您可以这样修正您的程序,例如:
#include <stdio.h>
int main()
{
float BlocksLeft = 0xFF0000 - 0xFF7FF;
int BLeft = 0xFF0000 - 0xFF7FF;
printf("%08x\n", (int) BlocksLeft); // Works because BlocksLeft's value is non negative
// or
printf("%08x\n", (unsigned int) BlocksLeft);
// or
printf("%.8e\n", BlocksLeft);
printf("%08x\n", BLeft);
}