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?
- New Content published on w3resource:
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- React - JavaScript Library
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework