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

C#利息计算器输出异常求助:计算逻辑问题排查

C#利息计算器逻辑错误定位与修正

任务要求

输入初始存款金额,按年利率5%计算连续3年的复利本息和,需一次性输出初始金额及3年的本息和,所有结果保留两位小数并遵循四舍五入规则(例:输入100.00,输出100.00、105.00、110.25、115.76)。

现有代码问题分析

你的代码存在两个核心问题:

  1. 利息计算逻辑错误:你把每年的利息固定成初始存款的5%,这是单利计算,但题目要求的是复利(每年的利息基于当年的本息和计算)。比如第二年的利息应该是第一年本息和的5%,而不是初始存款的5%。
  2. 未输出初始金额:任务要求包含初始金额,但你的代码只输出了三年的本息和,漏掉了初始值。

另外,用double处理货币类计算容易出现精度问题,推荐用decimal类型,计算时也要用decimal字面量(比如0.05m)避免隐式转换。

修正后的代码

// 读取输入并转换为decimal类型,适合货币计算
decimal deposit = decimal.Parse(Console.ReadLine());

// 计算各年本息和(复利逻辑)
decimal year1 = deposit * 1.05m;
decimal year2 = year1 * 1.05m;
decimal year3 = year2 * 1.05m;

// 输出初始金额及三年的结果,保留两位小数
Console.WriteLine($"{deposit:N2}");
Console.WriteLine($"{year1:N2}");
Console.WriteLine($"{year2:N2}");
Console.WriteLine($"{year3:N2}");

或者更直观的分步计算写法:

decimal deposit = decimal.Parse(Console.ReadLine());
Console.WriteLine($"{deposit:N2}");

decimal year1 = deposit + deposit * 0.05m;
Console.WriteLine($"{year1:N2}");

decimal year2 = year1 + year1 * 0.05m;
Console.WriteLine($"{year2:N2}");

decimal year3 = year2 + year2 * 0.05m;
Console.WriteLine($"{year3:N2}");

验证结果

  • 输入100.00时,输出:
    100.00
    105.00
    110.25
    115.76
    
  • 输入100.23时,输出:
    100.23
    105.24
    110.50
    116.02
    

完全符合任务要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 22:01:13