C# Compound Interest Calculator (beginner) - c#

C# beginner, trying to create a program where a user enters an amount, years, and rate and then calculates the total amount. The rate will be divided by 100 to get the decimal value and the years will be multiplied by 12 to get the monthly rate.
Here is the code:
class Program
{
static void Main(string[] args)
{
CompoundClass program = new CompoundClass();
Console.Write("Please enter the initial balance for your account: ");
double balance = Convert.ToDouble(Console.ReadLine());
Console.Write("Please enter the annual interest rate: ");
double interestRate = Convert.ToDouble(Console.ReadLine());
program.Rate(interestRate);
Console.Write("How many years will you acrue interest? ");
double anualAmount = Convert.ToDouble(Console.ReadLine());
program.Years(anualAmount);
Console.WriteLine($"Your balance after {anualAmount} years is {totalAmount:C}\n");
Console.ReadLine();
}
}
class CompoundClass
{
public double rate;
public double yearlyRate;
public double balance;
public void Rate(double interestRate)
{
if (interestRate > 0)
{
rate = interestRate / 100;
}
}
public void Years(double anualAmount)
{
if (anualAmount > 0)
{
yearlyRate = anualAmount * 12;
}
}
public void addMethod(double totalAmount)
{
for (int i = 1; i < yearlyRate + 1; i++)
{
totalAmount = balance * Math.Pow(1 + rate / yearlyRate, yearlyRate * i);
}
}
}
I keep getting the error:
CS0103The name 'totalAmount' does not exist in the current context.
I don't know if any information is being pulled correctly and stored/calculated.

You are having that error because the 'totalAmount' variable can only be accessed inside CompoundClass. This is because it is created with a default access modifier private.
You created an object for CompoundClass
CompoundClass program = new CompoundClass();
You have accessed the methods using the object. Regarding your question for annualAmount or interestRate, you didn't access the variables from CompoundClass, you have just passed them from Program class. However you can still access rate, yearlyRate, and balance through the object like program.rate and so on. This is because you have declared them as public.
public double rate;
public double yearlyRate;
public double balance;
If you want to access totalAmount as well, please declare that as public.
program.addMethod(balance);
Console.WriteLine($"Your balance after {anualAmount} years is {program.totalAmount:C}\n");

You are trying to print out (from program) the value of a variable that you have not declared (totalAmount from within program).
Since it is looking like you want to calculate totalAmount you want to change your addMethod to return the calculated amount instead of accepting totalAmount as a parameter.
For example in program do
double totalAmount = addMethod();
Console.WriteLine($"Your balance after {anualAmount} years is {totalAmount:C}\n");
And implement addMethod to return the value:
public void addMethod()
{
double calculatedTotalAmount = 0;
for (int i = 1; i < yearlyRate + 1; i++)
{
calculatedTotalAmount = balance * Math.Pow(1 + rate / yearlyRate, yearlyRate * i);
}
return calculatedTotalAmount;
}
Effectively, you are assigning the value calculated within the scope of the method to totalAmount, which is declated in the outer scope.

Related

I am not able to convert final answer into decimal form

I am not able to bring my final output in decimal terms
When i tried to convert double to decimal it gives error
using System;
namespace Recurring_Deposit_Calc
{
class Program
{
private double _amount, _month,_a;
private double _b,_simpleintrest,_matureAmount,_x;
public void Calulate() {
Console.WriteLine("Intrest Rate :6.8%");
Console.WriteLine("Enter amount you deposit per month:");
_amount = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter months:");
_month = Convert.ToInt32(Console.ReadLine());
//Calculting Simple Intrest
_simpleintrest = _amount * _month*_a/ 2 * 12*_b;
_a = _month + 1;
_b = 7.65/100;
//Calculating Maturity Amount
_x = _amount * _month;
_matureAmount = _x + _simpleintrest;
Console.WriteLine("Amount is :{0}",_matureAmount);
}
}
Code link
Output
If you want convert to decimal, you can use the Convert.ToDecimal method.
Console.WriteLine("Amount is :{0}",_matureAmount.ToString("0.00"));
If you want upto 1 decimal place, use .ToString("0.0").
I got the output as expected
New problem how to reduce the place value of final answer
private double p, r = 6.8, i, totalDeposit, maturityAmount;
private int n;
public static void Main(string[] args){
Console.WriteLine("Interest Rate :6.8%");
Console.WriteLine("Please enter per month deposit amount:");
p = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter months:");
n = Convert.ToInt32(Console.ReadLine());
//recurring deposit simple interest formula
//i=p*(n(n+1)/2*12)*r/100
i = p * (n * (n + 1) * r / 2400);
totalDeposit = p * n;
maturityAmount = totalDeposit + i;
Console.WriteLine("Amount of maturity = " +
"Totoal money deposited+Interest:{0}+{1}={2}", totalDeposit, i, maturityAmount);
}
Output
******Recurring Deposit Calculator******
Interest Rate :6.8%
Please enter per month deposit amount:
4567
Enter months:
7
Amount of maturity = Totoal money
deposited+Interest:31969+724.6306666666667=32693.630666666668

Payroll Array Issues (unsure why calculations do not begin) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
public struct pay
{
public string name;
public int rate;
public int hours;
public int gross;
public int wtd;
public int ssd;
public int md;
public int net;
}
static void Main(string[] args)
{
pay[] myPay = new pay[3];
for (int i = 0; i<= 2; i++)
{
Console.WriteLine("Enter name: ");
myPay[i].name = Console.ReadLine();
Console.WriteLine("Enter pay rate: ");
myPay[i].rate = Convert.ToInt16(Console.ReadLine());
Console.WriteLine("Enter hours worked: ");
myPay[i].hours = Convert.ToInt16(Console.ReadLine());
}
Console.WriteLine("Name\tRate\tHours\tGross\t W/T\tSS\tMed\tNet");
for (int i = 0; i<=2; i++)
{
int gross = (myPay[i].rate * myPay[i].hours);
int wtd = (myPay[i].gross * (1/20));
int ssd = (myPay[i].gross * (3 / 100));
int md = (myPay[i].gross * (1 / 100));
int net = (myPay[i].gross - (md + ssd + wtd));
Console.WriteLine(myPay[i].name + "\t" + myPay[i].rate + "\t" + myPay[i].hours + "\t" + myPay[i].gross + "\t" + myPay[i].wtd + "\t" + myPay[i].ssd + "\t" + myPay[i].md + "\t" + myPay[i].net);
}
Console.ReadLine();
}
}
The code is intended to take the name, rate, and hours worked of an employee to find gross pay. Then, costs will be taken from gross pay (each indicated with WTD, SD, and MD) to find the net income for the employee.
For whatever reason, the calculations for gross pay never begin, and therefore the following calculations do not register either. Any help would be greatly appreciated!
If you need a decimal value, you cant store it in an int
int (C# Reference)
If you are going to be calculating money you need to use a decimal
decimal (C# Reference)
Struct
public struct pay
{
public string name;
public int rate;
public int hours;
public decimal gross;
public decimal wtd;
public decimal ssd;
public decimal md;
public decimal net;
public void Calculate()
{
gross = (rate * hours);
wtd = (gross * (1 / (decimal)20));
ssd = (gross * (3 / (decimal)100));
md = (gross * (1 / (decimal)100));
net = (gross - (md + ssd + wtd));
}
}
Usage
static void Main(string[] args)
{
pay[] myPay = new pay[3];
for (int i = 0; i <= 2; i++)
{
Console.WriteLine("Enter name: ");
myPay[i].name = Console.ReadLine();
Console.WriteLine("Enter pay rate: ");
myPay[i].rate = Convert.ToInt16(Console.ReadLine());
Console.WriteLine("Enter hours worked: ");
myPay[i].hours = Convert.ToInt16(Console.ReadLine());
}
Console.WriteLine("Name\tRate\tHours\tGross\t W/T\tSS\tMed\tNet");
for (int i = 0; i <= 2; i++)
{
myPay[i].Calculate();
Console.WriteLine($"{myPay[i] .name}\t{myPay[i] .rate}\t{myPay[i] .hours}\t{myPay[i] .gross}\t{myPay[i] .wtd}\t{myPay[i] .ssd}\t{myPay[i] .md}\t{myPay[i] .net}");
}
Console.ReadLine();
}
Output
Enter name:
dfg
Enter pay rate:
4
Enter hours worked:
5
Enter name:
dh
Enter pay rate:
56
Enter hours worked:
7
Enter name:
fjh
Enter pay rate:
56
Enter hours worked:
4
Name Rate Hours Gross W/T SS Med Net
dfg 4 5 20 1.00 0.60 0.20 18.20
dh 56 7 392 19.60 11.76 3.92 356.72
fjh 56 4 224 11.20 6.72 2.24 203.84
Disclaimer, i just fixed up the glaring problems, however i am not liable for anyone you maim or otherwise injure with this code
I think your problem is using int as a variable, you should use decimal variable when calculating salaries or anything that involves currency to have exact result.

Having incorrect solutions when program executes,

I've been working on a two class BMI Calculator for my class. I finally have managed to debug on get the program to execute. However I noticed that it wont let me enter height or weight as a decimal.
Example
putting 6.4 for height causes it to crash
Putting 6 height and 220 weight always seems to declare underweight and show incorrect bmi reading
example:
Height 6
Weight 220
BMI: score $0.09
It's calculating the BMI wrong. Looking at the code I can't seem to identify why its calculating this wrong.
-Edit- Managed to get it to take decimals! (Thank you everyone!) However it still seems to be messing up calculating the BMI
-Edit- Code Works!
(Code Part 1) Updated Mk2
using System;
namespace Calculator
{
public class BMICalc
{
private const
decimal REQ = 703;
private decimal weightPerson;
private decimal heightPerson;
public BMICalc()
{
}
public BMICalc(decimal weiP, decimal heiP)
{
this.weightPerson = weiP;
this.heightPerson = heiP;
}
public decimal SetBmi()
{
decimal bmi;
bmi = Convert.ToDecimal((this.weightPerson * 0.45m) / ((this.heightPerson * 12 * 0.025m) * (this.heightPerson * 12 * 0.025m)));
if (bmi < 18.5m)
{
Console.WriteLine("UnderWeight");
Console.ReadLine();
}
if (bmi > 18.5m && bmi < 25.0m)
{
Console.WriteLine("Normal");
Console.ReadLine();
}
if (bmi > 25.0m && bmi < 29.9m)
{
Console.WriteLine("OverWeight");
Console.ReadLine();
}
if (bmi > 29.9m && bmi < 40.0m)
{
Console.WriteLine("Obese");
Console.ReadLine();
}
return bmi;
}
public override string ToString()
{
return "\tCalculator" +
"\n\n Weight:" + this.weightPerson +
"\n\n Height:" + this.heightPerson +
"\n\n BMI Score:" + SetBmi().ToString();
}
}
}
Code (Part 2) Updated Mk 2
namespace Calculator
{
public class App
{
public static void Main() //
{
decimal heiP, weiP;
heiP = InputHeight();
weiP = InputWeight();
BMICalc bmiCal = new BMICalc(weiP, heiP);
Console.Clear();
Console.WriteLine(bmiCal.ToString());
Console.ReadKey();
}
public static decimal InputHeight()
{
decimal hNumber;
Console.Write("Please enter your height: ");
hNumber = Convert.ToDecimal(Console.ReadLine());
return hNumber;
}
public static decimal InputWeight()
{
Decimal wNumber;
Console.Write("Please enter your weight: ");
wNumber = Convert.ToDecimal(Console.ReadLine());
return wNumber;
}
}
}
You're input parameters into the constructor expects weight (weiP), height (heiP) (in that order) while you're passing height, weight from BMICalc bmiCal = new BMICalc(heiP, weiP);
That's the reason the value being output is incorrect. Interchange the parameters and it should be fine.
EDIT
Since you're entering the weight in Lbs and height in feet, you would need to convert feet into inches ( multiplying by 12) and then also multiplying the height and weight by the conversion metric.
So the formula would be:
bmi = Convert.ToDecimal((this.weightPerson * 0.45) / ((this.heightPerson * 12 * 0.025) * (this.heightPerson * 12 * 0.025)));
The currency comes in when it uses the ToString() overridden method. The format specified there is for currency.

If statement not working in C#

I'm using a tutorial to write a simple app that calculates how many years it will take for a bank account to reach a target amount.
I'm trying to use an "If" statement, so if the person's beginning balance is more than their target amount, it prints "Your balance is bigger than the target amount", but when I write this into my code, it always prints the above no matter what amounts the user inputs.
Here's the code:
double balance, interestRate, targetBalance; //creating three doubles
Console.WriteLine("What is your current balance?"); //writing to the console
balance = Convert.ToDouble(Console.ReadLine()); //reading what the user inputs & converting it to a double
Console.WriteLine("What is your current annual interest (in %)?");
interestRate = 1 + Convert.ToDouble(Console.ReadLine()); //same as above
Console.WriteLine("What balanec would you like to have?");
targetBalance = Convert.ToDouble(Console.ReadLine()); //same as above
int totalYears = 0; //creates an int variable for the total years
do
{
balance *= interestRate; //multiplying balance x interest rate
++totalYears; // adding 1 to the total years
}
while (balance < targetBalance); //only do the above when balance is less than target balance
if (balance < targetBalance)
{
Console.WriteLine("In {0} year{1} you'll have a balance of {2}.", totalYears, totalYears == 1 ? "" : "s", balance); //writing the results to the console
}
else if (targetBalance < balance)
{
Console.WriteLine("Your balance is bigger than the target amount");
}
Console.ReadKey(); //leaving the results there until the user inputs a key
The only way for your do-while loop to exit is when the balance is >= the target balance. Because of this, your first if statement will never evaluate to true.
You probably want to do your targetBalance < balance check before you enter your do-while loop. If the balance is greater than the target, start over. And then after the loop, there is no need to do the if check around your 'In x years...' dialog.
It works fine here.
But please check your balance,targetBalance first. You didn't notice that what would happen If they are equal.
I think you want this...
double balance, interestRate, targetBalance; //creating three doubles
Console.WriteLine("What is your current balance?"); //writing to the console
balance = Convert.ToDouble(Console.ReadLine()); //reading what the user inputs & converting it to a double
Console.WriteLine("What is your current annual interest (in %)?");
interestRate = 1 + Convert.ToDouble(Console.ReadLine()); //same as above
Console.WriteLine("What balanec would you like to have?");
targetBalance = Convert.ToDouble(Console.ReadLine()); //same as above
int totalYears = 0; //creates an int variable for the total years
if (balance < targetBalance)
{
do
{
balance *= interestRate; //multiplying balance x interest rate
++totalYears; // adding 1 to the total years
}
while (balance < targetBalance); //only do the above when balance is less than target balance
Console.WriteLine("In {0} year{1} you'll have a balance of {2}.", totalYears, totalYears == 1 ? "" : "s", balance); //writing the results to the console
}
}
else if (targetBalance < balance)
{
Console.WriteLine("Your balance is bigger than the target amount");
}
Console.ReadKey(); //leaving the results there until the user inputs a key

Infinity in interest calculation?

Thanks to Laurence Burke in my other question for the isMaybeMoney function, I am able to determine whether an input is money or not.
What I'm doing now is trying to calculate the total after interest but I keep getting Infinity written to the screen. What in the world is wrong with my interestsaccrued function? It's supposed to be $3,522.55 when I use $1,234 as the starting balance with 3.5% interest.
Can someone please help me out?
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;
}
You are multiplying total by the rate each step through the while loop, which seems reasonable enough, but you also multiply total by the value of the variable "money", which as far as I can tell is the starting balance.
So you multiply by the starting balance 360 times. If only my savings accounts worked like that! I'm not sure if the rest of the logic is correct, but for a start, try moving the
total = total * money;
to be under the line
float total = 1;
(or better yet just change from
float total = 1;
to
float total = money;
and get rid of the line
total = total * money;
altogether)
The codes you have is not evaluate. NO BENEFIT of construct loop for interest calculate!
This is not needful yet introduce much of risk for high complication
Here is codes you want for use of FUNCTIONARY encapsulate :
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);
}
thanks,
PRASHANT :)

Categories