请求开发具备房贷计算与收支分析功能的C#个人费用追踪应用代码
C# Personal Budget Calculator Application
Got it, here's a complete console-based C# implementation that checks all your boxes—no persistent storage, in-memory data handling, and all the calculation logic you need. I kept it straightforward so you can easily adapt the core logic to a GUI if you want later.
Key Features Covered
- Capture monthly pre-tax income, estimated taxes, and regular expenses (groceries, utilities, transit, etc.)
- Toggle between Renting and Homeownership with targeted input fields for each
- Calculate monthly mortgage payments using the standard amortization formula
- Warn if mortgage payments exceed 1/3 of pre-tax income (per lending guidelines)
- Compute remaining disposable income after all expenses are deducted
Full Code Implementation
using System; // Enum to define housing selection options public enum HousingType { Renting, Homeownership } // Class to store all general income/expense inputs public class BudgetInputs { public decimal MonthlyGrossIncome { get; set; } public decimal MonthlyEstimatedTaxes { get; set; } public decimal Groceries { get; set; } public decimal Utilities { get; set; } public decimal Transportation { get; set; } public decimal Communication { get; set; } public decimal OtherExpenses { get; set; } public HousingType SelectedHousing { get; set; } public HousingSpecificDetails HousingDetails { get; set; } } // Class to store housing-specific data (rent or mortgage details) public class HousingSpecificDetails { // For renting scenario public decimal MonthlyRent { get; set; } // For homeownership scenario public decimal PropertyTotalValue { get; set; } public decimal DownPayment { get; set; } public decimal AnnualInterestRate { get; set; } public int LoanTermMonths { get; set; } } class Program { static void Main(string[] args) { // All data stays in memory (local objects) — no cross-run persistence var userBudget = new BudgetInputs(); var housingData = new HousingSpecificDetails(); Console.WriteLine("=== Personal Budget Calculator ==="); // Capture general income and expense data userBudget.MonthlyGrossIncome = GetValidDecimalInput("Enter monthly gross income (pre-tax): "); userBudget.MonthlyEstimatedTaxes = GetValidDecimalInput("Enter monthly estimated tax deduction: "); userBudget.Groceries = GetValidDecimalInput("Enter monthly grocery expenses: "); userBudget.Utilities = GetValidDecimalInput("Enter monthly utility expenses: "); userBudget.Transportation = GetValidDecimalInput("Enter monthly transportation expenses (including fuel): "); userBudget.Communication = GetValidDecimalInput("Enter monthly communication expenses: "); userBudget.OtherExpenses = GetValidDecimalInput("Enter other monthly expenses: "); // Handle housing type selection Console.WriteLine("\nSelect your housing type:"); Console.WriteLine("1. Renting"); Console.WriteLine("2. Homeownership"); var housingChoice = GetValidIntInput("Enter your choice (1/2): ", 1, 2); userBudget.SelectedHousing = housingChoice == 1 ? HousingType.Renting : HousingType.Homeownership; // Capture housing-specific inputs if (userBudget.SelectedHousing == HousingType.Renting) { housingData.MonthlyRent = GetValidDecimalInput("\nEnter monthly rent amount: "); } else { housingData.PropertyTotalValue = GetValidDecimalInput("\nEnter total property value: "); housingData.DownPayment = GetValidDecimalInput("Enter down payment amount: "); housingData.AnnualInterestRate = GetValidDecimalInput("Enter annual interest rate (e.g., 5 for 5%): "); housingData.LoanTermMonths = GetValidIntInput("Enter loan term in months (e.g., 360 for 30 years): ", 1, int.MaxValue); } userBudget.HousingDetails = housingData; // Calculate and display results decimal housingCost = 0; if (userBudget.SelectedHousing == HousingType.Homeownership) { housingCost = CalculateMonthlyMortgage(housingData); Console.WriteLine($"\nCalculated monthly mortgage payment: {housingCost:C}"); // Check mortgage-to-income ratio warning if (housingCost > userBudget.MonthlyGrossIncome / 3) { Console.WriteLine("⚠️ Warning: Monthly mortgage payment exceeds 1/3 of gross income. Mortgage approval likelihood is low."); } } else { housingCost = housingData.MonthlyRent; Console.WriteLine($"\nMonthly rent: {housingCost:C}"); } // Compute total expenses and disposable income decimal totalMonthlyExpenses = userBudget.MonthlyEstimatedTaxes + userBudget.Groceries + userBudget.Utilities + userBudget.Transportation + userBudget.Communication + userBudget.OtherExpenses + housingCost; decimal disposableIncome = userBudget.MonthlyGrossIncome - totalMonthlyExpenses; Console.WriteLine("\n=== Monthly Budget Summary ==="); Console.WriteLine($"Gross Income: {userBudget.MonthlyGrossIncome:C}"); Console.WriteLine($"Total Expenses: {totalMonthlyExpenses:C}"); Console.WriteLine($"Disposable Income: {disposableIncome:C}"); Console.WriteLine("\nPress any key to exit..."); Console.ReadKey(); } // Helper to get valid non-negative decimal input private static decimal GetValidDecimalInput(string prompt) { decimal value; while (true) { Console.Write(prompt); if (decimal.TryParse(Console.ReadLine(), out value) && value >= 0) { break; } Console.WriteLine("Invalid input. Please enter a non-negative number."); } return value; } // Helper to get valid integer input within a range private static int GetValidIntInput(string prompt, int min, int max) { int value; while (true) { Console.Write(prompt); if (int.TryParse(Console.ReadLine(), out value) && value >= min && value <= max) { break; } Console.WriteLine($"Invalid input. Please enter a number between {min} and {max}."); } return value; } // Calculate fixed-rate monthly mortgage payment using amortization formula private static decimal CalculateMonthlyMortgage(HousingSpecificDetails details) { decimal loanAmount = details.PropertyTotalValue - details.DownPayment; decimal monthlyInterestRate = (details.AnnualInterestRate / 100) / 12; // Handle 0% interest edge case if (monthlyInterestRate == 0) { return loanAmount / details.LoanTermMonths; } // Amortization formula: M = P[r(1+r)^n]/[(1+r)^n - 1] decimal compoundFactor = (decimal)Math.Pow((double)(1 + monthlyInterestRate), details.LoanTermMonths); decimal monthlyPayment = loanAmount * (monthlyInterestRate * compoundFactor) / (compoundFactor - 1); return Math.Round(monthlyPayment, 2); } }
Quick Implementation Notes
- In-Memory Storage: All user data is stored in local objects (
BudgetInputs,HousingSpecificDetails) and is discarded when the app closes—no file or database persistence as requested. - Mortgage Logic: Uses the standard fixed-rate amortization formula and handles 0% interest as a edge case.
- Input Validation: Helper methods ensure users enter valid, non-negative values to avoid calculation errors.
- Adaptability: You can drop this core logic into a Windows Forms, WPF, or Blazor app by replacing the console input/output with UI controls.
内容的提问来源于stack exchange,提问作者philani




