C# 使用for循环的直线折旧
我不确定我的代码在这个问题上哪里出错了。列表框应显示如下所示:C# 使用for循环的直线折旧,c#,winforms,C#,Winforms,我不确定我的代码在这个问题上哪里出错了。列表框应显示如下所示: 0 10,000.00 0.00 0.00 1 8,000.00 2,000.00 2,000.00 2 6,000.00 2,000.00 4,000.00 3 4,000.00 2,000.00 6,000.0
0 10,000.00 0.00 0.00
1 8,000.00 2,000.00 2,000.00
2 6,000.00 2,000.00 4,000.00
3 4,000.00 2,000.00 6,000.00
4 2,000.00 2,000.00 8,000.00
5 0.00 2,000.00 10,000.00
但结果是这样的:
0 8,000.00 0.00 2,000.00
1 6,000.00 2,000.00 4,000.00
2 4,000.00 2,000.00 6,000.00
3 2,000.00 2,000.00 8,000.00
4 0.00 2,000.00 10,000.00
5 -2000.00 2,000.00 12,000.00
我似乎不知道发生了什么事,因为我是c#的新手。这是我的密码:
private void ComputeDepreciation(double AssetValue,double years)
{
double AnnualDepreciation, TotalDepreciation;
AnnualDepreciation = 0;
TotalDepreciation = 0;
AnnualDepreciation = AssetValue / years;
for (years = 0; years <= double.Parse(textBox2.Text); years++)
{
AssetValue = AssetValue - AnnualDepreciation;
TotalDepreciation = TotalDepreciation + AnnualDepreciation;
lstOutput.Items.Add(String.Format(strOutput, years, AssetValue, AnnualDepreciation, TotalDepreciation));
}
}
private void计算折旧(双倍资产价值,双倍年限)
{
双年度折旧,总折旧;
年折旧率=0;
总折旧=0;
年折旧=资产价值/年;
(年=0;年我想你想要这样的东西:
0 8,000.00 0.00 2,000.00
1 6,000.00 2,000.00 4,000.00
2 4,000.00 2,000.00 6,000.00
3 2,000.00 2,000.00 8,000.00
4 0.00 2,000.00 10,000.00
5 -2000.00 2,000.00 12,000.00
确保将字体设置为单空格样式,以便保留列格式
您可以通过将其.DataSource
属性设置为字符串集合来填充列表框
,就像下面的按钮单击方法一样。此外,建议使用decimal
来处理与避免任何愚蠢行为(如1.199999997
)相关的任何金额
private IList<string> ComputeDepreciation(decimal assetValue, int noYears)
{
List<string> table = new List<string>();
// Add header
table.Add($"{"Yrs",3} {"Asset Value",15} {"Actual Depr.",18} {"Total Depr.",14}");
// Year 0 values
int year = 0;
decimal totalDepreciation = 0m;
decimal actualDepreciation, annualDepreciation = assetValue/noYears;
do
{
// Cannot depreciate more than the value
actualDepreciation = Math.Min(annualDepreciation, assetValue);
// Add formatted row with column widths 3, 15, 18, 14
// Currency formatted with "C2", two decimals and currency symbol.
table.Add($"{year,3} {assetValue,15:C2} {actualDepreciation,18:C2} {totalDepreciation,14:C2}");
// adjust values each year
assetValue -= actualDepreciation;
totalDepreciation += actualDepreciation;
year++;
} while (actualDepreciation>0m);
return table;
}
private void fillButton_Click(object sender, EventArgs e)
{
listBox1.DataSource = ComputeDepreciation(10000m, 5);
}
私有IList计算折旧(十进制资产价值,整数年)
{
列表=新列表();
//添加标题
加上($”{“年”,3}{“资产价值”,15}{“实际折旧”,18}{“总折旧”,14}”);
//第0年值
整年=0;
十进制总折旧=0米;
十进制实际折旧,年折旧=资产价值/年;
做
{
//折旧不能超过价值
实际折旧=数学最小值(年折旧、资产价值);
//添加列宽为3、15、18、14的格式化行
//格式为“C2”、两位小数和货币符号的货币。
表.增加($“{年,3}{资产价值,15:C2}{实际折旧,18:C2}{总折旧,14:C2}”);
//每年调整数值
资产价值-=实际折旧;
总折旧+=实际折旧;
年份++;
}而(实际沉降>0m);
返回表;
}
私有无效填充按钮\单击(对象发送者,事件参数e)
{
listBox1.DataSource=计算折旧(10000m,5);
}
似乎您希望第一行的总折旧为零,但您的for循环从第0年开始执行操作。您可以从1而不是0设置开始索引,并将第一行从循环中删除。您的参数double years
根本不使用,而是从带有double.Parse(textBox2.text)的文本框中读取
。不要这样做,请将计算与UI分开。