gpt4 book ai didi

c - Linux gcc (5.4.0) 中的 float 是否遵守 IEEE754 规则?

转载 作者:可可西里 更新时间:2023-11-01 11:48:29 24 4
gpt4 key购买 nike

我的编程环境是gcc 版本 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.4)

我的代码是这样的:

#include <stdio.h>

typedef unsigned char *byte_pointer;

void show_bytes(byte_pointer start, int len){
int i;
for (i = 0; i<len; i++)
printf(" %.2x", start[i]);
printf("\n");
}

void show_float(float x){
show_bytes((byte_pointer)&x, sizeof(float));
}

int main(){
int y = 0xffffff;
float f = y;
show_float(f);
return 0;
}

机器给出结果:00 00 00 e0

我认为根据 IEEE 754 是不对的;但我不知道为什么。而 Windows 中 VS 2013 中的相同代码给出了正确的答案:ff ff 7f 4b

gcc 5.4.0 不是采用 IEEE 754 吗?还是我的代码有问题?

最佳答案

Does gcc 5.4.0 not adopt the IEEE 754?
Or are there some problem in my code?

gcc 5.4.0 和 IEEE 754 不是问题。当然代码不符合


通过重新排序函数,但代码相同,我收到 2 个警告并且可以复制 OP 的输出 00 00 00 e0

警告:函数“show_float”的隐式声明[-Wimplicit-function-declaration]
警告:“show_float”类型冲突

我怀疑 OP 没有发布真实代码。 - 或者它不是全部在一个文件中。实际代码通常存在代码传递 double 的问题 - 由于缺少事先声明/定义,但 show_float() 需要一个 float .

#include <stdio.h>

typedef unsigned char *byte_pointer;

void show_bytes(byte_pointer start, int len){
int i;
for (i = 0; i<len; i++)
printf(" %.2x", start[i]);
printf("\n");
}

int main(){
int y = 0xffffff;
float f = y;
show_float(f); // code lacks proto-type, so assumes it needs to pass a double
return 0;
}

void show_float(float x){
show_bytes((byte_pointer)&x, sizeof(float));
}

通过声明原型(prototype)或重新排序代码来修复。

#include <stdio.h>

typedef unsigned char *byte_pointer;
void show_bytes(byte_pointer start, int len);
void show_float(float x);

/* the 3 functions in any order */

关于c - Linux gcc (5.4.0) 中的 float 是否遵守 IEEE754 规则?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45485732/

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