Scala 中的整数除法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11303337/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 04:18:52  来源:igfitidea点击:

Int division in scala

scala

提问by Karel Bílek

I have two Intvalues in Scala.

Int在 Scala 中有两个值。

scala> val a = 3
a: Int = 3

scala> val b = 5
b: Int = 5

Now, I want to divide them and get Float. With as little boilerplate as possible.

现在,我想将它们分开并获得 Float。尽可能少的样板文件。

If I do a/b, I get

如果我这样做a/b,我得到

scala> a/b
res0: Int = 0

I cannot do simple Java (float).

我不能做简单的 Java (float)

scala> ((Float)a)/b
<console>:9: error: value a is not a member of object Float
              ((Float)a)/b
                      ^

What should I do?

我该怎么办?

回答by Karel Bílek

The following line followed by its result should solve your problem.

以下行后跟其结果应该可以解决您的问题。

scala> a.toFloat/b
res3: Float = 0.6

回答by Kristian Domagala

Alternative answer that uses type ascription:

使用类型归属的替代答案:

scala> (a:Float)/b
res0: Float = 0.6