使用for循环将基本复合兴趣作为列表输出到MessageBox中

时间:2014-10-29 00:45:31

标签: for-loop messagebox

我需要输出基本的复合兴趣,它将使用for循环

显示在消息框中

消息框需要显示一个标题为" Years"和右栏显示"金额"。

我的代码仅显示消息框5次,而我需要将其全部显示在列表中

这是我到目前为止所做的:

  private void button1_Click(object sender, EventArgs e)
    {


        decimal amount;
        decimal principal = 1000;
        double rate = 0.05;
        string msg;
        msg = "Years \t Amount";
        msg += Environment.NewLine;



        for (int year = 1; year <= 5; year++)
        {
            amount = principal * ((decimal)Math.Pow(1.0 + rate, year));
            msg += amount.ToString("C");
            msg  += Environment.NewLine;





        }

        MessageBox.Show(msg, "Compund Interest");

2 个答案:

答案 0 :(得分:1)

private void button1_Click(object sender, EventArgs e)
{
    string amount = "";
    decimal principal = 1000;
    double rate = 0.05;

    for (int year = 1; year <= 5; year++) {
        amount += string.Format("{0:C}", principal * Convert.ToDecimal(Math.Pow(1.0 + rate, year))) + Environment.NewLine;
    }
    MessageBox.Show(amount, "Compound Inerest");
}

答案 1 :(得分:0)

  private void button1_Click(object sender, EventArgs e)
    {


        decimal amount;
        decimal principal = 1000;
        double rate = 0.05;
        string msg;
        // start building string here i.e. msg = "header \t header"  \t places a tab
        // add a carriage return msg += Enviornment.Newline
        for (int year = 1; year <= 5; year++)
        {
            amount = principal * ((decimal)Math.Pow(1.0 + rate, year));
            // don't overwrite msg but append to it msg += "year number use your counter \t" += what you are already doing below.
            msg = amount.ToString("C");
           // then add your carriage return again.


        }
        MessageBox.Show(msg);
}