Scala将两个整数相除并得到浮点结果 [英] Scala Divide two integers and get a float result

查看:1897
本文介绍了Scala将两个整数相除并得到浮点结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我执行以下操作

 println(3/4)
 >0

我想获得小数而不是整数。由于我在实际代码中进行打印的方式,如果可能的话,我希望在println中进行强制转换。

I would like to get a decimal answer instead of an integer. Because of the way I am printing in my actual code I would prefer to cast within the println if that is possible.

推荐答案

如果您输入的是数字,只需至少输入其中一个作为浮点数(我假设您的意思是 Float 而不是 Double ):

If you're typing the number, just type at least one of them as a float (I assume you mean Float not Double):

println(3f/4)

如果您已经有变量中的数字,请使用至少将其中之一转换为Float

If you already have the numbers in variables, convert at least one of them with toFloat

val x = 3
println(x.toFloat/4)

(在每种情况下,如果至少有一个,编译器会将另一个转换为 Float 进行匹配。)

(In each case, if you have at least one, the compiler will convert the other to Float to match.)

这篇关于Scala将两个整数相除并得到浮点结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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