Scala,检查Double的溢出

Scala,检查Double的溢出,scala,exception,overflow,Scala,Exception,Overflow,这里是Scala noobie,专业地用C#、R和Perl编程。如何检查双重溢出?你必须自己滚吗?请参阅下面的代码和输出。据我所知,有999个半径的水溢出。我想为溢出抛出一个错误。谢谢 case class LessThanZeroEx(private val message:String = "Less than zero") extends Exception(message){} import scala.io.StdIn.readLine println(&qu

这里是Scala noobie,专业地用C#、R和Perl编程。如何检查双重溢出?你必须自己滚吗?请参阅下面的代码和输出。据我所知,有999个半径的水溢出。我想为溢出抛出一个错误。谢谢

case class LessThanZeroEx(private val message:String = "Less than zero") extends Exception(message){}  
import scala.io.StdIn.readLine

println("Scala exception test")
println("Get area and circumference of a circle.")
val radius:Integer = getNumFromCon("Please enter a radius: ")
val circum = getCircum(radius)
val area = getArea(radius)
println("The circumference is " + circum + " and the area is " + area)

def getNumFromCon(prompt:String):Int = 
{
  val input:String = readLine(prompt)
  var rv:Integer = 0
  try
  {
    rv = input.toInt
    if(rv < 0) throw LessThanZeroEx("message")
  } catch
  {
    case fe : NumberFormatException => {
      println("Your input was not in the correct format")
      rv = getNumFromCon(prompt)}
    case ltz : LessThanZeroEx => {
      println("Your input was less than zero")
      rv = getNumFromCon(prompt)}
  }
  return rv
}

def getCircum(radius:Integer):Double = 
{
  return 2.0 * math.Pi * radius
}

def getArea(radius:Integer):Double = 
{
  return math.Pi * radius * radius
}

您的代码不会溢出。最后一个结果是用科学符号表示的:它不是
~3.14
,而是
~3.14*10^8
(这是正确的)


从技术上讲,
Double
操作可能会溢出,但您需要非常努力:
Double。最大值约为
10^308

很好,谢谢。正如我所说,Scala是新手,没想到会出现这种符号。非常感谢。
>scala exception-test.scala
Scala exception test
Get area and circumference of a circle.
Please enter a radius: 99
The circumference is 622.0353454107791 and the area is 30790.749597833565

>scala exception-test.scala
Scala exception test
Get area and circumference of a circle.
Please enter a radius: 999
The circumference is 6276.9021218724065 and the area is 3135312.609875267

>scala exception-test.scala
Scala exception test
Get area and circumference of a circle.
Please enter a radius: 9999
The circumference is 62825.56988648868 and the area is 3.1409643664750016E8