如何正确显示年利率列表?

时间:2019-06-16 02:32:14

标签: c#

我想知道如何使用For Loop创建每年加息列表的输出。我的不断循环,不会破裂。

        double deposited;
        double year;
        double interestRate;
        double calculation;

        Console.Write("Enter the amount of deposited: ");
        deposited = double.Parse(Console.ReadLine());

        Console.Write("Enter the number of years: ");
        year = double.Parse(Console.ReadLine());

        Console.Write("Enter the interest rate as a percentage of 1.0: ");
        interestRate = double.Parse(Console.ReadLine());

        Console.WriteLine("Year\t Balance");
        calculation = deposited * Math.Pow((1 + interestRate), year);

        for (int i = 0; i < calculation; i++)
        {
            for (int t = 1; t < year; t++)
            {
                Console.WriteLine(string.Format("{0}\t {1:C}", t,
                calculation));                   
            }              
        }

1 个答案:

答案 0 :(得分:0)

这不是一个无限循环,只是由于您的calculation变量以及计算和使用它的方式而导致它确实很长。例如,如果我存入100个10年期和1.0个利率,则计算循环将循环102400次。考虑到它将在内部循环中循环10次,因此将调用Console.WriteLine()。102p次。

考虑到您想要多年的简单利率:

using System;

public class MainClass {
  public static void Main (string[] args) {
        int year;
        double deposited;
        double interestRate;

        Console.Write("Enter the amount of deposited: ");
        deposited = double.Parse(Console.ReadLine());

        Console.Write("Enter the number of years: ");
        year = int.Parse(Console.ReadLine());

        Console.Write("Enter the interest rate as a percentage of 1.0: ");
        interestRate = double.Parse(Console.ReadLine());

        Console.WriteLine("Year\t Balance");

        for(int i = 0; i < year; i++){
          var balance = deposited + (deposited * interestRate * (i + 1));
          Console.WriteLine("{0}\t\t{1}", (i + 1), balance);
        }
  }
}

注意:要计算1%的利率,请输入“ 0.01”,分别输入10%,“ 0.1”和100%“ 1.0”,依此类推。