从整数获取浮点值 [英] Getting float value from integers
本文介绍了从整数获取浮点值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从整数除法中得到浮点数或实数?例如:
How can I get a float or real value from integer division? For example:
double result = 30/233;
产生零.我想要带小数位的值.
yields zero. I'd like the value with decimal places.
然后如何格式化,以便与字符串一起使用时仅显示两位小数?
How can I then format so only two decimal places display when used with a string?
推荐答案
您可以在分子或分母中添加一个小数:
You could just add a decimal to either the numerator or the denominator:
double result = 30.0 / 233;
double result = 30 / 233.0;
对两个数字之一进行类型转换也可以.
Typecasting either of the two numbers also works.
对于问题的第二部分,如果您使用printf样式的格式字符串,则可以执行以下操作:
As for the second part of the question, if you use printf-style format strings, you can do something like this:
sprintf(str, "result = %.2f", result);
基本上,.2"代表小数点后要输出的位数.
Bascially, the ".2" represents how many digits to output after the decimal point.
这篇关于从整数获取浮点值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文