klren0312 / daliy_knowledge

知识积累,正确使用方式是watch
21 stars 4 forks source link

js化简比例 #824

Open klren0312 opened 7 months ago

klren0312 commented 7 months ago
function gcd(a, b) {
  // 辗转相除法求最大公约数
  while (b !== 0) {
    let t = b;
    b = a % b;
    a = t;
  }
  return a;
}

function simplifyRatio(num1, num2) {
  // 计算比值
  let ratio = num1 / num2;
  // 确保比值不为0
  if (ratio === 0) return { simplifiedRatio: [0, 1], message: "比值不能为0" };
  // 计算最大公约数
  let divisor = gcd(num1, num2);
  // 简化比值
  let simplifiedNum1 = num1 / divisor;
  let simplifiedNum2 = num2 / divisor;
  return { simplifiedRatio: [simplifiedNum1, simplifiedNum2], message: `最简比值为 ${simplifiedNum1}:${simplifiedNum2}` };
}

// 使用函数
let result = simplifyRatio(60, 48);
console.log(result.message); // 输出: 最简比值为 5:4