gpt4 book ai didi

c - 减去十六进制

转载 作者:太空宇宙 更新时间:2023-11-04 06:20:24 26 4
gpt4 key购买 nike

当我将一个变量声明为 float 并减去两个十六进制数时,每次编译和运行时我都会得到不同的答案。如果我声明一个整数变量,每次编译和运行代码时结果都保持不变。我不明白为什么每次使用相同的两个数字 (0xFF0000 - 0xFF7FF) 进行编译时,将结果存储在 float 中都会发生变化

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 stackoverflow.exe stackoverflow.c
stackoverflow.c: In function 'main':
stackoverflow.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);
}

关于c - 减去十六进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36288387/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com