到目前为止我的代码是..
private void button1_Click(object sender, EventArgs e)
{
string display;
double initialfee = 12000.00;
double increase,newfee;
double rate = 0.02;
listBox1.Items.Clear();
for (int year = 1; year <= 5; year++)
{
increase = initialfee * rate * year;
newfee = increase + initialfee;
display = "year " + year.ToString() + ": " + " Amount " + "$" + newfee;
listBox1.Items.Add(display);
答案 0 :(得分:2)
你不需要乘以年份。 试试这个
string display;
double initialfee = 12000.00;
double increase=0,newfee;
double rate = 0.02;
for (int year = 1; year <= 5; year++)
{
if(year>1)
{
increase = initialfee * rate;
}
initialfee = increase + initialfee;
display = "year " + year.ToString() + ": " + " Amount " + "$" + initialfee;
Console.WriteLine(display);
}
输出:
year 1: Amount $12000
year 2: Amount $12240
year 3: Amount $12484.8
year 4: Amount $12734.496
year 5: Amount $12989.18592
答案 1 :(得分:2)
这是一个计算的解决方案。
private void button1_Click(object sender, EventArgs e)
{
string display;
double initialfee = 12000.00;
double increase,newfee;
double rate = 0.02;
listBox1.Items.Clear();
for (int year = 1; year <= 5; year++)
{
newfee = initialfee + (initialfee * 2/100 * year);
display = "year " + year.ToString() + ": " + " Amount " + "$" + newfee;
}
}
这个计算第一年为2%,明年为4%,依此类推。
如果每年需要增加2%的化合物,那么,
private void button1_Click(object sender, EventArgs e)
{
string display;
double initialfee = 12000.00;
double increase,newfee;
double rate = 0.02;
listBox1.Items.Clear();
for (int year = 1; year <= 5; year++)
{
if(year == 1)
newfee = initialfee;
else
newfee = newfee + (newfee * 2 / 100);
display = "year " + year.ToString() + ": " + " Amount " + "$" + newfee;
}
}
希望这有帮助!
答案 2 :(得分:0)
Linq 解决方案:
using System.Linq;
...
// Please, see separation:
// Model: here we define condition
// initial conditions
double initialfee = 12000.00;
double rate = 0.02;
int years = 5;
// Business logic: here we obtain data
// please, notice formatting (here is C# 6.0 string interpolation)
// which is easier to read and maintain then contructing string from chunks added.
var data = Enumerable
.Range(1, years)
.Select(year => $"Year {year}: Amount: {Math.Pow(1.0 + rate, year - 1) * initialfee:f2}")
.ToArray();
// Representation: UI representation
// Add items in one go to prevent redrawing and blinking
listBox1.Items.AddRange(data);
结果是
Year 1: Amount: 12000.00
Year 2: Amount: 12240.00
Year 3: Amount: 12484.80
Year 4: Amount: 12734.50
Year 5: Amount: 12989.19
我知道,您正在寻找循环解决方案,但在真实世界中,我们通常更喜欢使用数据查询。