我想知道如何使用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));
}
}发布于 2019-06-16 11:09:15
这不是一个无限循环,只是由于你的calculation变量以及你计算和使用它的方式,它真的很长。例如,如果我存入利率为10年的100,利率为1.0,计算循环将循环102400次。考虑到它将在内部循环中循环10次,它将是Console.WriteLine()被调用的1024000次。
考虑到你想要多年来的简单利率:
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”,依此类推。
https://stackoverflow.com/questions/56615638
复制相似问题