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

如何在ListBox中同时显示自定义文本与计算结果?

ListBox显示「Year x:」前缀及计算修正方案

给计算结果添加「Year x:」前缀

直接在向ListBox添加条目时,把年份标识和格式化后的金额拼接起来即可,修改循环内的代码:

原代码:

listFutureValue.Items.Add(futureValue.ToString("c"));

替换为以下任意一种写法:

  • 字符串插值(语法简洁,推荐使用):
listFutureValue.Items.Add($"Year {i}: {futureValue.ToString("c")}");
  • 兼容旧版.NET的string.Format写法:
listFutureValue.Items.Add(string.Format("Year {0}: {1:c}", i, futureValue));

修正计算结果不正确的问题

你当前循环里的futureValue /= i逻辑错误,这不是逐年计算终值的正确方式。正确做法是每年单独计算对应年份的累计终值,将循环部分代码替换为:

listFutureValue.Items.Clear();
for (int i = 1; i <= years; i++)
{
    // 计算第i年的终值,传入i*12个月作为参数
    decimal yearlyFutureValue = CalculateFutureValue(monthlyInvestment, interestRateMonthly, i * 12);
    // 添加带前缀的条目
    listFutureValue.Items.Add($"Year {i}: {yearlyFutureValue.ToString("c")}");
}

这样既能显示正确的逐年终值,又能带上要求的「Year x:」前缀。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 22:25:29