每日一图.jpg
效果图
19.png
代码
/**
* Created on 2021/11/26 13:48
*
* @author Gong Youqiang
*/
// 四则运算表达式计算器
fun main() {
while (true) {
println("=======请输入表达式=======")
val input = readLine()
try {
input?.let {
val result = calculate(it)
println("$input = $result")
println("是否继续使用(y/n)")
val cmd = readLine()
cmd?.let {
if (it == "n"){
exitProcess(-1)
}else {
// 继续使用
}
}
}
}catch (e : Exception) {
e.printStackTrace()
}
}
}
fun calculate(input: String): String {
when {
input.contains("+") -> {
val nums = input.trim().split("+")
return operate(nums[0].toDouble(),nums[1].toDouble(),"+").toString()
}
input.contains("-") -> {
val nums = input.trim().split("-")
return operate(nums[0].toDouble(),nums[1].toDouble(),"-").toString()
}
input.contains("*") -> {
val nums = input.trim().split("*")
return operate(nums[0].toDouble(),nums[1].toDouble(),"*").toString()
}
input.contains("/") -> {
val nums = input.trim().split("/")
return operate(nums[0].toDouble(),nums[1].toDouble(),"/").toString()
}
else -> {
println("您输入的表达式有误")
return "input error"
}
}
}
fun operate(nums: Double, nums2: Double,operate:String): Double {
return when(operate){
"+" -> nums + nums2
"-" -> nums - nums2
"*" -> nums * nums2
"/" -> nums / nums2
else -> 0.0
}
}
网友评论