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

编写计算活到90岁时剩余天数、周数、月数的函数

计算活到90岁剩余的天数、周数和月数函数实现

要实现一个能计算活到90岁时剩余天数、周数和月数的函数,先看原代码存在的几个问题:

  • 计算逻辑错误:yourAge - 90会得到负数,应该用90 - yourAge获取剩余年数
  • 变量作用域混乱:计算剩余量的变量定义在函数外部,函数未利用传入的参数
  • 弹窗内容格式混乱:字符串拼接缺少空格,显示结果会杂乱无章

以下是修正后的完整实现:

function ageCalculation(yourAge) {
  const remainingYears = 90 - yourAge;
  const remainingDays = remainingYears * 365;
  const remainingWeeks = remainingYears * 52;
  const remainingMonths = remainingYears * 12;
  
  alert(`You have ${remainingDays} Days, ${remainingWeeks} Weeks, ${remainingMonths} Months left until you turn 90.`);
}

// 获取用户输入并执行计算
const yourAge = prompt("Your Age?");
// 验证输入有效性
if (!isNaN(yourAge) && yourAge >= 0 && yourAge <= 90) {
  ageCalculation(Number(yourAge));
} else {
  alert("Please enter a valid age between 0 and 90.");
}

关键修正说明

  • 把计算逻辑移入函数内部,依赖传入的yourAge参数,保证变量作用域合理
  • 修正剩余年数的计算方式,确保结果为正数
  • 使用ES6模板字符串拼接弹窗内容,让输出格式更清晰
  • 添加输入验证,避免无效输入导致的错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 03:40:33