利息计算中的无穷大
本文关键字:无穷大 计算 | 更新日期: 2023-09-27 18:27:01
感谢Laurence Burke在我关于isMaybeMoney函数的另一个问题中的回答,我能够确定输入是否为货币。
我现在正在做的是计算利息后的总额,但我一直在屏幕上写Infinity。我感兴趣的功能到底出了什么问题?当我用1234美元作为起始余额,利息为3.5%时,应该是3522.55美元。
有人能帮帮我吗?
static float money;
static void Main()
{
string[] myMaybeBalances = Accounts.GetStartingBalances();
myIsMaybeMoneyValidator Miimv = new myIsMaybeMoneyValidator();
ArrayList interests = Miimv.interestsAccrued(myMaybeBalances);
foreach (object interest in interests)
{
Console.WriteLine(interest);
}
Console.ReadLine();
}
public ArrayList interestsAccrued(string[] myMaybeBalances)
{
ArrayList interests = new ArrayList();
foreach (string myMaybeBalance in myMaybeBalances)
{
bool myResult = isMaybeMoney(myMaybeBalance);
if (myResult == true)
{
decimal[] rates = Accounts.GetRates();
for (int i = 0; i < rates.Length; i++)
{
decimal rate = rates[i];
float total = 1;
int n_X_t = 360;
while (n_X_t != 0)
{
rate = (1 + rates[i] / 12);
float myRate;
float.TryParse(rate.ToString(), out myRate);
total = total * myRate;
total = total * money;
n_X_t = n_X_t - 1;
}
interests.Add(total);
}
}
}
return interests;
}
public bool isMaybeMoney(object theirMaybeMoney)
{
string myMaybeMoney = theirMaybeMoney.ToString();
float num;
bool isValid = float.TryParse(myMaybeMoney,
NumberStyles.Currency,
CultureInfo.GetCultureInfo("en-US"), // cached
out num);
money = num;
return isValid;
}
在while循环中,你将total乘以每一步的速率,这似乎很合理,但你也将total除以变量"money"的值,据我所知,这是起始余额。
所以你乘以起始平衡360倍。要是我的储蓄账户能这样就好了!我不确定其余的逻辑是否正确,但首先,请尝试移动
total = total * money;
在线下
float total = 1;
(或者最好只是从中更改
float total = 1;
至
float total = money;
并消除线路
total = total * money;
总共)
您所拥有的代码不会进行求值。利息计算的构造循环没有好处!这是不必要的,但引入了高并发症的很大风险
以下是您想要使用FUNCTIONARY封装的代码:
static void Main()
{
var interests = new List<decimal>();
foreach (string possibleBalance in Accounts.GetStartingBalances())
foreach (decimal rate in Accounts.GetRates())
{
decimal balance;
if (!decimal.TryParse(possibleBalance, NumberStyles.Currency, CultureInfo.CurrentCulture, out balance))
continue;
decimal interest = CalculateInterestAccrued(balance, rate, 12, 30);
interests.Add(interest);
}
foreach (decimal interest in interests)
Console.WriteLine(interest);
Console.ReadKey();
}
static decimal CalculateInterestAccrued(decimal principal, decimal rate, int compoundsPerYear, int years)
{
return principal * (decimal)Math.Pow((double)(1 + rate / compoundsPerYear), compoundsPerYear * years);
}
谢谢,
PRASHANT:)