首页 > 解决方案 > 我遇到了一个while循环数学问题

问题描述

我得到了一个数学问题,必须专门用一个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.

标签: javascriptwhile-loop

解决方案


最后的if陈述应该基于total,而不是points_winner。如果total0,则该团队有资格。

如果总数小于 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])


推荐阅读