int到float转换产生警告? [英] int to float conversion produces a warning?

查看:216
本文介绍了int到float转换产生警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

令我惊讶的是,我看到即使值可以转换,int到float转换总是给出警告。为什么是这样?

  int i = 0; 
float f = 0; // warning here

//我认为这是一个隐式转换,
//意味着它是可转换的没有警告。
f = i; //此处另一个警告

警告是:

 警告C4244:'=':从'int'转换为'float',可能会丢失数据


解决方案

这取决于你的 int 类型中有多少位。 IEEE754单精度浮点数是一个32位值,但其中一些位分配给指数,这意味着不是所有的精度都可用。



如果您的 int 类型比你的 float 更精确,那么你可能会在高端损失精度。



换句话说,它可能无法区分 INT_MAX INT_MAX - 1 double )虽然,技术上,你可能会发现一个具有256位 int 类型的实现,在这种情况下你必须找到另一种方法: - )



这个回答简要概述了浮点格式的工作原理,包括32位中只有23位可用于尾数的精度。


It's surprising for me to see that even when the value can be converted, an int to float conversion always give a warning. Why is this?

int i = 0;
float f = 0; // warning here

// I thought this was an implicit conversion,
// meaning it is convertible with no warnings.
f = i;      // another warning here

The warning is:

warning C4244: '=' : conversion from 'int' to 'float', possible loss of data

解决方案

It depends on how many bits you have in your int type. A float that is IEEE754 single precision is a 32-bit value but some of those bits are assigned to the exponent, meaning not all are available for precision.

If your int type has more precision than your float, then you may suffer loss of precision at the high end.

In other words, it may not be able to distinguish between INT_MAX and INT_MAX - 1.

Solution in that case is to use a wider floating point type (double) although, technically, you may find an implementation that has a 256-bit int type in which case you'll have to find another way :-)

This answer has a brief overview of how the floating point formats work, including the fact that only 23 of the 32 bits are available for the precision of the mantissa.

这篇关于int到float转换产生警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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