Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

Scala Programming: Check which number is nearest to the value 100 among two given integers

Scala Programming Basic Exercise-20 with Solution

Write a Scala program to check which number is nearest to the value 100 among two given integers. Return 0 if the two numbers are equal.

Sample Solution:

Scala Code:

object scala_basic {
  def test(x: Int, y: Int): Int = {
    val x_abs = Math.abs(x - 100)
    val y_abs = Math.abs(y - 100)
    if (x_abs == y_abs) 0
    else if (x_abs < y_abs) x
    else y
    }
     
   def main(args: Array[String]): Unit = {
      println("Result: " + test(78,95));
      println("Result: " + test(95,95));
      println("Result: " + test(99,70));      
    }
  }

Sample Output:

Result: 95
Result: 0
Result: 99

Scala Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Scala program to check the largest number among three given integers.
Next: Write a Scala program to check whether two given integers are in the range 40..50 inclusive, or they are both in the range 50..60 inclusive.

What is the difficulty level of this exercise?