这是我的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MortgageApplication
{
class Program
{
static void Main(string[] args)
{
string input = "", year, principle, month;
double r, y, p;
bool valid = false;
y = 0;
r = 0;
p = 0;
while (valid == false)
{
Console.WriteLine("Enter the duration of the loan (Number of Years): ");
input = Console.ReadLine();
if (double.TryParse(input, out y))
{
Console.WriteLine(y);
valid = true;
}
}
valid = false;
while (valid == false)
{
Console.WriteLine("Enter the princple ammount: ");
input = Console.ReadLine();
if (double.TryParse(input, out p))
{
Console.WriteLine(p);
valid = true;
}
}
valid = false;
while (valid == false)
{
Console.WriteLine("Enter the Interest Rate ");
input = Console.ReadLine();
if (double.TryParse(input, out r))
{
valid = true;
}
}
r = r / 100;
Console.WriteLine(r);
double top = p * r / 1200;
Console.WriteLine(top);
double x = (1 + (r / 1200.0));
Console.WriteLine(x);
double n = -12 * y;
Console.WriteLine(n);
double buttom = (1 - (Math.Pow(x, n)) );
Console.WriteLine(buttom);
double solution = top / buttom;
Console.WriteLine(solution);
Console.ReadLine();
}
}
}
这是一个简单的抵押贷款应用程序。我有功能但公式不正确。
不确定是不是因为我正在使用双打,或者问题与我的编码有关。
(p r / 1200.0)/(1 - (1.0 + r / 1200.0)^( - 12.0 n)),
其中
- p = principal(美元)
- n =年数
- r =利率(百分比)
- m =每月付款
答案 0 :(得分:1)
所以我认为直接的答案是你将利率除以100,然后再将其除以1200.你要么不要除以100除以开始,要么除以12之后(我喜欢第二种选择)因为它清楚地表明你在谈论12个月。)
为了减少重复代码,您可能会考虑的另一件事是分解出一个从用户那里得到双倍的新函数。类似的东西:
private static double GetDoubleFromUser(string prompt)
{
double result;
while (true)
{
if (prompt != null) Console.Write(prompt);
var input = Console.ReadLine();
if (double.TryParse(input, out result)) break;
Console.WriteLine("Sorry, that is not a valid number. Please try again...");
}
return result;
}
现在,当你需要一个double时,你只需要调用这个函数并传递提示字符串。这使您的代码更清晰,更易于阅读。例如,您的代码现在可以写成:
private static void Main()
{
double years = GetDoubleFromUser("Enter the duration of the loan (in years): ");
double principal = GetDoubleFromUser("Enter the princple ammount: ");
double rate = GetDoubleFromUser("Enter the interest rate: ") / 100;
Console.WriteLine("\nBased on these values entered:");
Console.WriteLine(" - Number of years .... {0}", years);
Console.WriteLine(" - Principal amount ... {0:c}", principal);
Console.WriteLine(" - Interest rate ...... {0:p}", rate);
double monthlyRate = rate / 12;
double payments = 12 * years;
double result =
principal *
(monthlyRate * Math.Pow(1 + monthlyRate, payments)) /
(Math.Pow(1 + monthlyRate, payments) - 1);
Console.WriteLine("\nYour monthly payment will be: {0:c}", result);
Console.ReadLine();
}