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

如何基于首次计算结果循环运算得到15条记录并以表格形式在网页展示

完整实现代码

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>复利计算工具</title>
</head>
<body>
    <table width="350" border="0">
        <tr>
            <td>初始金额:</td>
            <td><input class="form-control" name="amount" id="amount" value="" type="number"/></td>
        </tr>
        <tr>
            <td>每期增长率(%):</td>
            <td><input class="form-control" name="inputOne" id="inputOne" value="" type="number"/></td>
        </tr>
        <tr>
            <td><input type="button" name="calculate" id="calculate" value="计算" onClick="calculate()"/></td>
            <td><input type="button" name="clear" id="clear" value="清空" onClick="clearForm()"/></td>
        </tr>
    </table>
    <!-- 结果展示容器 -->
    <div id="resultContainer" style="margin-top: 20px;"></div>

<script>
function calculate() {
    // 读取输入值
    const initialAmount = Number(document.getElementById('amount').value);
    const rate = Number(document.getElementById('inputOne').value);
    const resultContainer = document.getElementById('resultContainer');
    
    // 输入合法性校验
    if (isNaN(initialAmount) || isNaN(rate) || initialAmount <=0 || rate <0) {
        resultContainer.innerHTML = '<p style="color: red;">请输入合法的正数值</p>';
        return;
    }

    let currentValue = initialAmount;
    // 拼接表格HTML
    let tableHtml = `
    <table class="s-table" border="1" cellpadding="8" cellspacing="0">
        <thead>
            <tr>
                <th>序号</th>
                <th>值</th>
            </tr>
        </thead>
        <tbody>
    `;

    // 循环计算15次
    for (let i = 1; i <=15; i++) {
        currentValue = currentValue * (1 + rate / 100);
        // 按示例规则取整
        const showValue = Math.round(currentValue);
        tableHtml += `
        <tr>
            <td>${i}</td>
            <td>${showValue}</td>
        </tr>
        `;
    }

    tableHtml += `
        </tbody>
    </table>
    `;
    // 渲染结果到页面
    resultContainer.innerHTML = tableHtml;
}

function clearForm() {
    // 清空输入框
    document.getElementById('amount').value = '';
    document.getElementById('inputOne').value = '';
    // 清空结果
    document.getElementById('resultContainer').innerHTML = '';
}
</script>
</body>
</html>

核心逻辑说明

  • 固定循环15次,每次以上一次的计算结果为基数计算下一期数值,和你给出的示例计算规则完全匹配,输入1500、10时前4条输出和预期一致
  • 增加了基础输入校验,避免空值、负数输入导致计算异常
  • 清空功能可同时清除输入内容和已生成的结果表格

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 04:06:03