给我一个数学问题,必须专门用while循环解决。我尝试了太多方法来解决它,但不幸的是,它们似乎没有用。
这是数学问题本身:
世界杯小组赛即将结束,佩皮想知道他最喜欢的球队是否有资格参加比赛。众所周知,以下规则适用-如果一支球队在一场比赛中进球多于获得的进球,则获胜并获得3分;如果进球和进球数相等,则该团队获得1分;在输的情况下,积分数不会改变。如果从所有比赛中得分的进球总数大于或等于收到的进球数,则该团队最终排名。编写一个计算团队是否合格的程序。
从控制台读取两行:
- 团队名称-文字;
- 参加比赛-区间[1…10]中为正整数;
每场比赛都有两个新行:
- 进球数-[1…10000]区间内的正整数;
- 收到的目标-在[1…10000]区间内为整数的正数;
控制台上打印两行:
- 如果团队符合条件:
“ {team name}以{points}分结束了小组赛阶段。”
“目标差异:{目标差异}。”- 如果团队没有资格:
“ {team name}已从小组阶段中删除。”
“目标差异:{目标差异}。”
function solve(input) {
let name = input.shift();
let matches_played = Number(input.shift());
let matches = 0;
let points_winner = 0;
let points_loser = 0;
let goalDifference = 0;
let total = 0;
while (matches <= matches_played) {
let first_team = Number(input.shift());
let second_team = Number(input.shift());
if (first_team > second_team) {
points_winner = points_winner + 3;
} else if (first_team === second_team) {
points_winner = points_winner + 1;
} else if (first_team < second_team) {
points_winner = points_winner + 0;
}
goalDifference = first_team - second_team;
total = total + goalDifference;
matches++;
}
if (points_winner >= points_loser) {
console.log(`${name} has finished the group phase with ${points_winner} points.`)
} else {
console.log(`${name} has been eliminated from the group phase.`)
console.log(`Goal difference: ${goalDifference}`)
}
}
solve(['Brazil', 3, 4, 2, 0, 0, 1, 1])
显示输入后,预期输出为:
Brazil has finished the group phase with 5 points.
Goal difference: 2.
答案 0 :(得分:0)
最后的if
语句应基于total
,而不是points_winner
。如果total
至少为0
,则说明该小组合格。
如果总数小于0,则在显示不足的数量时将其转换为正数。
在最后显示目标差时,您需要使用total
。 goalDifference
仅包含与上一场比赛的区别。
while
条件应为matches < matches_played
。如果您使用<=
,则将浪费额外的时间并为缺少的数组元素获取undefined
,这会导致在将它们添加到NaN
时得到total
。>
function solve(input) {
let name = input.shift();
let matches_played = Number(input.shift());
let matches = 0;
let points_winner = 0;
let goalDifference = 0;
let total = 0;
while (matches < matches_played) {
let first_team = Number(input.shift());
let second_team = Number(input.shift());
if (first_team > second_team) {
points_winner = points_winner + 3;
} else if (first_team === second_team) {
points_winner = points_winner + 1;
} else if (first_team < second_team) {
points_winner = points_winner + 0;
}
goalDifference = first_team - second_team;
total = total + goalDifference;
matches++;
}
if (total >= 0) {
console.log(`${name} has finished the group phase with ${points_winner} points.`)
console.log(`Goal difference: ${total}`)
} else {
console.log(`${name} has been eliminated from the group phase.`)
console.log(`Goal difference: ${-total}`)
}
}
solve(['Brazil', 3, 4, 2, 0, 0, 1, 1])
solve(['Spain', 3, 2, 4, 1, 2, 3, 3])