浮来诠释转换 [英] Float to Int conversion

查看:143
本文介绍了浮来诠释转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读浮动编号,且最多2位小数,如如下:

I am reading "float" numbers which are up to 2 decimal places, such as below:

122
122.3
122.34

和需要将它们转换乘以(想象一下存储美元/美分)为整数值

and need to convert them to integer value by multiplying (imagine storing dollars/cents)

int i;
double d;

scanf( "%lf", &d );

i = d * 100;

例如 18.56 将被改造成 1855

有没有办法读取值作为双并将其转换为正确诠释?

Is there any way to read value as a double and convert it to int correctly?

TIA

推荐答案

要转换为int进行舍入最简单的方式:

The simplest way to convert to an int with rounding:

i = (int)floor(d * 100 + 0.5);

如果您的数字总是正面的:

If your numbers are always positive:

i = (int)(d * 100 + 0.5);

1.565 1.575和价值观之间将成为157的值2.135 2.145和之间将成为214。

Values between 1.565 and 1.575 will become 157. Values between 2.135 and 2.145 will become 214.

这样的话,如果你有一个数字,如1.56999,就会变成157。

That way, if you have a number like 1.56999, it will become 157.

这不解决$ ​​P $ pcision损失 - 不管它的意思。这只是四舍五入。

This does not "solve precision loss" - whatever that meant. It's just rounding.

如果值是完全两个数字之间(如d为1.125),那么你可能会得到意想不到的效果。在这种情况下,所有的数字只有两个小数位,所以这不是一个问题。如果用数字不仅限于更多小数位数,您可能想更仔细地如何处理数字像1.125考虑。

If a value is exactly between two numbers (e.g. d is 1.125) then you might get unexpected results. In this case, all numbers have only two decimal places, so this is not a problem. If numbers were not limited to more decimal places, you'd want to consider more carefully how to handle numbers like 1.125.

这篇关于浮来诠释转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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