将 float 转换为 int 指针并返回浮动? [英] Casting float to int pointer and back to float?

查看:79
本文介绍了将 float 转换为 int 指针并返回浮动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以向我解释这个 C 程序的行为吗?我试图了解它的行为...

Can some explain me the behavior of this C program I was trying to understand its behavior...

#include<stdio.h>
float x = 3.33,*y,z;
int *a,b;
int main() {
    a = (int *)&x;
    b = (int)x;
    y = (float *)a;
    z = (float)b;
    printf("\nOriginal Value of X: %f \ncasting via pointer A:%d and back Y: %f \ndirect casting B:%d and back Z:%f\n",x,*a,*y,b,z);
}

输出:

Original Value of X: 3.330000                                                                                                                                                   

casting via pointer A:1079320248 and back Y: 3.330000                                                                                                                           

direct casting B:3 and back Z:3.000000     

好的,那么为什么 A 的值是 1079320248 而它不是一些随机值,它对于 X = 3.33 总是相同的,并且它如果 X 更改为某些不同的值,我希望 A 之类的东西是 3 但它不是.

OK so why is the value of A is 1079320248 and its not some random value its always the same for X = 3.33 and it changes if X is changed to some different value I was expecting something like A to be 3 but its not.

推荐答案

在您的代码中不会发生通过指针 A 进行转换"这样的事情.您只是强迫编译器将 a 指向一个浮点值,假定它指向一个整数.

There is no such thing as 'casting via pointer A' happening in your code. You are just forcing the compiler to point a to a float value, where it is assumed to be pointing to an integer.

使用 Reymond Chen 在评论部分指出的 页面,我们得到 3.33 的二进制表示为:

Using the page pointed out by Reymond Chen in the comment section, we get the binary representation of 3.33 as:

01000000010101010001111010111000

现在,使用页面查找其 32 位有符号整数相等的.您将得到 1079320248,这是让您感到困惑的确切非随机数.

Now, use this page to find its 32-bit signed integer equivalent. You'll get 1079320248, which is the exact non-random number that puzzles you.

如果这对您没有任何意义,让我说得更清楚.ay 都指向同一个二进制值 01000000010101010001111010111000,它代表两个不同的值(3.33 作为 float 和 1079320248 作为 int)取决于您告诉编译器使用的数据类型.

If this doesn't make any sense to you, let me make it much clearer. Both a and y are pointing to the same binary value 01000000010101010001111010111000, which represents two different values (3.33 as float and 1079320248 as int) depending on the data type you tell the compiler to use for it.

更新:

出于学术兴趣,如果您希望 printf 语句为 A 打印 3,请将第三个参数替换为:

Just for academic interest, if you want the printf statement to print 3 for A, replace the third parameter with this:

(int) *((float *)a)

这篇关于将 float 转换为 int 指针并返回浮动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆