Python如何实现学生每累计50积分增加1颗星的循环逻辑
问题根源
原代码里的加星逻辑仅在累计积分刚好等于50时才会触发,无法覆盖两种常见情况:
- 单次加积分后总积分跳过50(比如从30直接加到70),判断条件不生效
- 总积分超过100,需要一次性加多颗星的场景
修改方案
根据需求「累计获得的积分每满50新增1颗星」,提供两种常用场景的修正方案:
场景1:累计总积分不清零,星数按累计积分总值计算
积分会一直累加不会扣除,星数等于总积分除以50的整数部分,仅需修改play方法即可:
def play(self, totalpoints): self.points += totalpoints # 计算当前积分对应应得总星数,减去已有星数就是本次新增的星数 add_star = self.points // 50 - self.star if add_star > 0: self.star += add_star
场景2:每满50就扣除对应积分,剩余积分滚入下一轮计算
凑够50分就兑换1颗星,同时扣掉50积分,剩下的分数留到下次凑满50再兑换,修改play方法如下:
def play(self, totalpoints): self.points += totalpoints # 循环处理直到积分不足50 while self.points >= 50: self.star += 1 self.points -= 50
完整可运行代码(以场景1为例)
class points: def __init__(self, studentname, points, star): self.studentname = studentname self.points = points self.star = star def play(self, totalpoints): self.points += totalpoints add_star = self.points // 50 - self.star if add_star > 0: self.star += add_star def displayInfo(self): print(self.studentname) print(f"累计积分:{self.points}") print(f"获得星数:{self.star}\n") student1 = points("Ana", 0, 0) student2 = points("Sandra", 0, 0) print("=====游戏前信息=====") student1.displayInfo() student2.displayInfo() student1.play(10) student2.play(5) student1.play(20) student2.play(10) student1.play(30) student2.play(30) student1.play(10) student2.play(5) student1.play(20) student2.play(10) student1.play(30) student2.play(30) print("=====游戏后信息=====") student1.displayInfo() student2.displayInfo()
运行后输出结果符合预期:student1累计积分120对应2颗星,student2累计积分90对应1颗星。
内容的提问来源于stack exchange,提问作者meliodas
相关产品推荐
相关产品推荐

