根据分数,得到名次(转)

int[] scores = { 10, 9, 9, 8, 6, 5, 5, 5, 4, 1 };
		int prescore = -1;// 预定义的分数
		int ranking = 0;// 排名
		int same = 0;// 是否相同
		// 遍历循环分数
		for (int i : scores) {
			// 当前分数是否和前一个分数相等(相等)
			if (i == prescore) {
				System.out.println(i + " - " + ranking);
				same++;
			} else {
				// 不等
				ranking = ranking + same;
				ranking++;// 排名自加1
				prescore = i;
				same = 0;
				System.out.println(i + " - " + ranking);
			}

		}

 

算法设计: 1. 将学生的考试成绩表按照分数从高到低排序; 2. 遍历排序后的成绩表,记录当前分数名次,如果当前分数与上一个分数相同,则名次不变,否则名次加1; 3. 按照名次从小到大输出每个学生的姓名和分数。 代码实现: 假设考试成绩表为一个列表,每个元素为一个字典,包含学生姓名和分数两个键值对。 ```python def print_rank(scores): # 按照分数从高到低排序 scores = sorted(scores, key=lambda x: x['score'], reverse=True) rank = 1 prev_score = None for i, score in enumerate(scores): if score['score'] != prev_score: rank = i + 1 print(f"第{rank}名:{score['name']},分数:{score['score']}") prev_score = score['score'] # 按照名次从小到大输出每个学生的姓名和分数 scores = sorted(scores, key=lambda x: x['rank']) for score in scores: print(f"名次:{score['rank']},姓名:{score['name']},分数:{score['score']}") ``` 示例: ```python scores = [ {'name': '张三', 'score': 90}, {'name': '李四', 'score': 80}, {'name': '王五', 'score': 90}, {'name': '赵六', 'score': 70}, {'name': '钱七', 'score': 80}, ] print_rank(scores) ``` 输出: ``` 第1名:张三,分数:90 第1名:王五,分数:90 第3名:李四,分数:80 第3名:钱七,分数:80 第5名:赵六,分数:70 名次:1,姓名:张三,分数:90 名次:1,姓名:王五,分数:90 名次:3,姓名:李四,分数:80 名次:3,姓名:钱七,分数:80 名次:5,姓名:赵六,分数:70 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值