Kotlin影院座位收益计算程序错误排查求助
影院收益计算代码问题排查
任务背景与目标
朋友计划扩展影院,需要根据座位数量计算全票售出时的总收益。需读取两个正整数:行数和每行座位数,票价规则如下:
- 总座位数≤60时,每张票10美元;
- 总座位数>60时,前半段行的票10美元,后半段行的票8美元(行数为奇数时,前半段取行数整除2的结果)。
问题代码
我编写了如下Kotlin代码,但运行结果错误,请帮忙找出问题:
fun main() { println("Enter the number of rows:") val rows = readln().toInt() println("Enter the number of seats in each row:") val seats = readln().toInt() val people = rows * seats //define the total seats val price1 = 10 val price2 = 8 val front = rows / 2 // the front rows val people1 = front * seats // people in the front part val back = rows - front // the back rows val people2 = back * seats //people in the back part val total1 = people * price1 // price in the 1st case val total2 = people1 * price1 + people2 * price2 // price in second case if (rows <= 9){ if (people > 60) println("Total income:$total1") else println( "Total income: $total2") } }
问题分析
你的代码存在三个核心错误:
- 判断逻辑完全颠倒:
规则要求总座位数≤60时用全价(total1),总座位数>60时用分段定价(total2),但你代码里写反了判断条件——people > 60时输出total1,完全不符合规则。 - 多余的行数限制:
规则里没有“行数≤9”的要求,你额外添加的if (rows <=9)会导致行数超过9时,程序直接跳过所有打印逻辑,完全不输出结果。 - 变量命名混淆:
people用来表示总座位数容易产生误解,建议改成totalSeats这类直观命名,提升代码可读性。
修正后的代码
fun main() { println("Enter the number of rows:") val rows = readln().toInt() println("Enter the number of seats in each row:") val seatsPerRow = readln().toInt() val totalSeats = rows * seatsPerRow val fullPrice = 10 val discountPrice = 8 val frontRows = rows / 2 val frontSeats = frontRows * seatsPerRow val backRows = rows - frontRows val backSeats = backRows * seatsPerRow val totalIncome = if (totalSeats <= 60) { totalSeats * fullPrice } else { frontSeats * fullPrice + backSeats * discountPrice } println("Total income: $$totalIncome") }
内容的提问来源于stack exchange,提问作者Abd ennour BOULMIS
相关产品推荐
相关产品推荐

