You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在函数内部console.log自身结果?求温度转换代码优化方案

温度转换代码优化方案

核心问题修复

原代码存在两个关键问题:

  • 函数末尾递归调用自身,导致无限循环无法正常执行
  • 分支内直接打印计算值,无法统一控制输出格式

精简优化实现

优化思路

  • 用转换规则映射表替代冗余的if-else分支,提升代码可读性和可维护性
  • 函数专注计算转换结果,输出格式统一处理,分离职责
  • 对结果做小数位数格式化,匹配示例要求的精度

优化后代码

// 定义温度转换规则:键为"源单位目标单位",值为对应转换函数
const conversionRules = {
  cf: num => num * 9/5 + 32,
  ck: num => num + 273.15,
  fc: num => (num - 32) * 5/9,
  fk: num => (num - 32)/1.8 + 273.15,
  kc: num => num - 273.15,
  kf: num => (num - 273.15) * 9/5 + 32
};

const convertTemperature = (fromUnit, toUnit, number) => {
  // 拼接规则键,转为小写兼容大小写输入
  const ruleKey = `${fromUnit.toLowerCase()}${toUnit.toLowerCase()}`;
  // 校验转换规则是否存在
  if (!conversionRules[ruleKey]) {
    console.error(`不支持 ${fromUnit} 到 ${toUnit} 的转换`);
    return;
  }
  // 计算结果并保留4位小数
  const result = conversionRules[ruleKey](number).toFixed(4);
  // 按指定格式输出
  console.log(`${number} ${fromUnit} to ${toUnit} is ${result}`);
};

// 调用示例
convertTemperature("f", "c", 10); // 输出:10 f to c is -12.2222
convertTemperature("f", "c", 100); // 输出:100 f to c is 37.7778

优化点说明

  • 消除冗余分支:用对象映射替代6个if-else,新增转换规则只需在conversionRules中添加键值对
  • 终止无限循环:移除原代码中的递归调用,改为直接计算结果
  • 统一格式输出:集中处理输出逻辑,确保所有转换都符合指定格式
  • 增强兼容性:自动将单位转为小写,避免大小写输入错误导致的失败
  • 添加错误处理:对不支持的转换给出明确提示,提升代码鲁棒性

内容的提问来源于stack exchange,提问作者jpop

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 21:53:13