把优秀判断封装成函数,用整数式 academic*7+quality*3 避免浮点误差。
OJ: luogu
题目 ID: P5742
难度:入门
标签:模拟结构体函数python
日期: 2026-07-15 21:15
题意
每名学生有学号、学业成绩和素质拓展成绩。优秀条件是:两项成绩总分大于 140,并且综合分数不小于 80。综合分数按 70% 和 30% 加权。
思路
题面提醒不要直接用浮点比较:
text
academic * 0.7 + quality * 0.3 >= 80两边同时乘以 10,可以改成整数判断:
text
academic * 7 + quality * 3 >= 800写一个函数 is_excellent(academic, quality),同时检查总分和综合分即可。
这题是函数封装和条件判断练习,不创建 brute.py。
Python 知识
/home/rainboy/mycode/hugo-blog/content/program_language/python/input_output_and_strings.md:一行三个整数用map(int, input().split())。/home/rainboy/mycode/hugo-blog/content/program_language/python/math_tools.md:能用整数比较时,避免浮点误差。- 布尔表达式可以直接作为函数返回值。
- 用函数封装判断规则,主循环只负责读入和输出。
代码
python
def is_excellent(academic, quality):
return academic + quality > 140 and academic * 7 + quality * 3 >= 800
n = int(input())
for _ in range(n):
student_id, academic, quality = map(int, input().split())
if is_excellent(academic, quality):
print("Excellent")
else:
print("Not excellent")cpp
/**
* Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
* rbook: -> https://rbook.roj.ac.cn https://rbook2.roj.ac.cn
* rainboy的学习导航网站: https://idx.roj.ac.cn
* create_at: 2026-07-27 00:00
* update_at: 2026-07-27 00:00
*/
#include <bits/stdc++.h>
using namespace std;
struct Student {
int id; // 学号
int ac; // 学业成绩
int qu; // 素质拓展成绩
};
int n;
// 判断是否为优秀:总分 > 140 且 综合分 >= 80
// 综合分 = academic * 0.7 + quality * 0.3
// 用整数避免浮点:academic*7 + quality*3 >= 800
bool is_excellent(Student &s) {
if (s.ac + s.qu <= 140) return false;
return s.ac * 7 + s.qu * 3 >= 800;
}
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
Student s;
cin >> s.id >> s.ac >> s.qu;
if (is_excellent(s)) cout << "Excellent\n";
else cout << "Not excellent\n";
}
return 0;
}Pythonic 写法
条件表达式:
python
n = int(input())
for _ in range(n):
_, academic, quality = map(int, input().split())
ok = academic + quality > 140 and academic * 7 + quality * 3 >= 800
print('Excellent' if ok else 'Not excellent')复杂度
每名学生只做常数次计算,时间复杂度是
总结
涉及小数权重判断时,优先把式子转成整数比较。这样既精确,也更符合 OJ 判题习惯。