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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace IndividualAssignmentLoan {
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
jmToday.Caption = Format(Now, "DDDD, D/MMMM/YYYY")
}
protected void btnCalculate_Click(object sender, EventArgs e)
{
double amount = double.Parse(jmLoanAmount.Text);
double downPay = double.Parse(jmDownPayment.Text);
double interest = double.Parse(jmInterestRate.Text);
int period = int.Parse(jmLoanPeriod.Text);
Double monthlyPay;
Double loanCost;
monthlyPay = ((amount * interest) / 1) - (Math.Pow(1/(1 + interest), period));
loanCost = monthlyPay * (period * 12);
jmMonthlyPayment.Text = monthlyPay.ToString();
jmTotalLoanCost.Text = loanCost.ToString();
}
}
}
Hi, I've written to the point where I do not understand where I am going wrong with my loan calculator. I've input my formula to get the loan amount as...
monthlyPay = ((amount * interest) / 1) - (Math.Pow(1/(1 + interest), period));
I've tried other ways of getting the correct amount, but nothing seems to give me the monthly amount I need. Can someone help me with the formula. Oh an my clock I have on top lol...
jmToday.Caption = Format(Now, "DDDD, D/MMMM/YYYY")
I hate it when teachers teach students to use double for money-related operations. Always use decimal, kids! 128-bit non-floating point goodness (https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/decimal)
Anyway, I think I deciphered what your teacher intended with the formula (your comment was ambiguous to say the least). I think you want:
double actualAmountToPay = amount - downPay;
double monthlyPay = actualAmountToPay * interest / (1 - 1 / Math.Pow((1 + interest), period));
double totalCost = monthlyPay * (period * 12);
Leave btnClick handling parsing and move monthly payment calculation to a separate method:
double CalculateMonthlyPayment(double amount, double downPayment, int termInYears, double interestRate)
{
int paymentsCount = MonthsPerYear * termInYears;
double principal = amount - downPayment;
if (interestRate == 0)
{
return principal / paymentsCount;
}
double monthlyRate = interestRate / MonthsPerYear;
double coefficient = Math.Pow(1 + monthlyRate, paymentsCount);
double monthlyPayment = principal * (monthlyRate * coefficient) / (coefficient - 1);
return monthlyPayment;
}
MonthsPerYear is a constant with an obvious value.
TotalPayment will be paymentsCount * MonthlyPayment
Keep in mind that you need to handle exception cases: amount <= 0, downPayment < 0, amount <= downPayment, termInMonths < 1. Also decide if you allow negative interest rate.
Related
I am calculating a monthly payment and taking in multiple inputs (cash, loan, loan period, interest rate) and then using GetPayment() to calculate monthly payment. I am required to use 2 different classes, one being program and the other being PaymentCalculator().
namespace ConsoleApp59
{
class Program
{
static void Main(string[] args)
{
PaymentCalculator calc1 = new PaymentCalculator();
calc1.SetCash(GetInput("cash flow: "));
calc1.SetLoan(GetInput("loan amount: "));
calc1.SetPeriod(GetInput("loan period (in months): "));
calc1.SetRate(GetInput("interest rate (ex. 10, 20): "));
calc1.GetPayment();
calc1.DisplayPayment();
ReadKey();
}
static double GetInput(string input)
{
Write("Please enter " + input);
double final = double.Parse(ReadLine());
return final;
}
}
public class PaymentCalculator
{
double cash, loan, period, rate, payment;
public PaymentCalculator()
{
cash = 0;
loan = 0;
period = 0;
rate = 0;
payment = 0;
}
public void SetCash(double input)
{
cash = input;
}
public void SetLoan(double input)
{
loan = input;
}
public void SetPeriod(double input)
{
period = input;
}
public void SetRate(double input)
{
rate = input;
}
public void GetPayment()
{
double firstCalculation = (loan * rate / 100);
double secondCalculation = (1 - 1 / Math.Pow(1 + rate / 100, period));
double payment = firstCalculation / secondCalculation;
}
public void DisplayPayment()
{
WriteLine("\t ----- Payment Calculator -----");
WriteLine("Monthly Payment: {0:F2}", payment);
}
}
}
The issue I am running into is when I run the program the output ALWAYS says this:
Monthly Payment: 0:00
It shouldn't be saying that, but instead any other number than 0.00. I have no clue why this is happening because I can't find any error in my code.
Please somebody tell me why this is happening and what can I do to fix it so I can get actual numbers as my answers.
The issue is in your GetPayment method.
public void GetPayment()
{
double firstCalculation = (loan * rate / 100);
double secondCalculation = (1 - 1 / Math.Pow(1 + rate / 100, period));
double payment = firstCalculation / secondCalculation; // <-- right here.
}
You are declaring a new local variable named payment, which shadows the class field that is used in your DisplayPayment method. Since it's never updated, the class field remains the initialized value of 0, which is what's ultimately displayed.
Instead, assign the calculated value to the class field.
payment = firstCalculation / secondCalculation;
I am not sure why but this is only returning 0, previously it was giving an error about not being able to convert double to int so I changed the Result var from Int to Double and the error went away.
protected void Button1_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(InterestDropdown.Text))
{
CalculatedPayment.Text = "Please select something for Interest
Rate";
}
else
{
int Loan1, Term1, Interest1;
Loan1 = Convert.ToInt32(LoanAmount.Text);
Term1 = Convert.ToInt32(Term.Text);
Interest1 = InterestDropdown.SelectedIndex;
Double Result = Loan1 * Interest1 / (1 - Math.Pow(1 + Interest1,
(Term1 * 12)));
CalculatedPayment.Text = Result.ToString();
}
}
You are most likely using int to represent a double. If Interest1 is less than 1 ie .5 it will be evaluated to 0.
Loan1 * 0 / anything = 0
Change your int if you are using decimal values.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
CS1001 = Identifier Expected
I took a snippet of code from Java that I would like to test in C#. It has a formula for calculating Experience needed to level up in a Video Game project I would like to use. I have just recently began teaching myself code, so converting this was trial and error for me, but I have eliminated the other 13 Errors and this one has me stuck.
Missing an identifier seems like a pretty rudimentary issue but it is also vague and i'm not sure when to begin to research. I have comment where the error occurs.
Any hints?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
float points = 0;
double output = 0; // Output, XP total at level
float minLevel = 2; // First level to Display
int maxLevel = 100; // Last Level to Display
int lvl = 0;
void Main()
{
for (lvl = 1; lvl <= maxLevel; lvl++)
{
points += Math.Floor(lvl + 300 * Math.Pow(2, lvl / 7.)); // Compile Error CS1001 at "));"
if (lvl >= minLevel)
Console.WriteLine("Level " + (lvl) + " - " + output + " EXP");
output = Math.Floor(points / 4);
}
}
}
}
Original JavaScript Code:
<SCRIPT LANGUAGE="JavaScript">
<!--
document.close();
document.open();
document.writeln('Begin JavaScript output:');
document.writeln('<PRE>');
points = 0;
output = 0;
minlevel = 2; // first level to display
maxlevel = 200; // last level to display
for (lvl = 1; lvl <= maxlevel; lvl++)
{
points += Math.floor(lvl + 300 * Math.pow(2, lvl / 7.));
if (lvl >= minlevel)
document.writeln('Level ' + (lvl) + ' - ' + output + ' xp');
output = Math.floor(points / 4);
}
document.writeln('</PRE>');
document.close();
// -->
</SCRIPT>
That doesn't look like the only problem... :)
See inline comments:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
float points = 0;
double output = 0;
float minLevel = 2;
int maxLevel = 100;
int lvl = 0;
void Main() //<-- Bad entry point public static void Main()
{
for (lvl = 1; lvl <= maxLevel; lvl++)
{
points += (float)Math.Floor(lvl + 300 * Math.Pow(2, lvl / 7.)); // <-- You have to explicitly specify the mantissa if you have a '.' is should be 7.0 or 7f
//^--- You also need to cast to a float here because the expression evaluates to a double
if (lvl >= minLevel)
Console.WriteLine("Level " + (lvl) + " - " + output + " EXP");
output = Math.Floor(points / 4);
}
}
}
}
When I run the code, it doesn't calculate and it doesn't show the calculations.
Wondering if my variables or something else is wrong or maybe in the wrong place.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Question_3_Retail_Price_Calculator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
decimal costPrice = 0;
decimal markUpRateA = 0.19m;
decimal markUpRateB = 0.14m;
decimal markUpRateC = 0.12m;
decimal markUpRate = 0m;
decimal markUpTotal = 0;
decimal totalCost = 0;
// Add the items to ListBox 1
listBox1.Items.Add("Markup Rate =");
listBox1.Items.Add("Markup Total =");
listBox1.Items.Add("Total Cost =");
try
{
// Read the cost price from the user
costPrice = decimal.Parse(textBox1.Text);
}
catch (System.Exception excep )
{
MessageBox.Show(excep.Message);
}
if (costPrice <= 50)
{
// Calculate the value of the product
costPrice = (costPrice / 100) * markUpRateA;
}
else if (costPrice >= 50 && costPrice < 100)
{
// Calculate the value of the product
costPrice = (costPrice / 100) * markUpRateB;
}
else if (costPrice < 100)
{
// Calculate the value of the product
costPrice = (costPrice / 100) * markUpRateC;
}
else if (markUpRate == markUpTotal)
{
// Calculate the total monetary amount
markUpTotal = costPrice * markUpRate;
}
else
{
// Calculate the Total Cost of the product
totalCost = costPrice + markUpTotal;
}
// Output the total Cost
MessageBox.Show("Total Cost is: €" + totalCost);
}
}
}
Need some help figuring this out! Thanks in advance!
You're setting your total cost in the last else condition which will be executed only if all the other if-else conditions are not executed. That is why this code isn't working as you expect.
Even if you enter a value >100, your result is never assigned to totalCost. Because execution enters this part of your code
else if (markUpRate == markUpTotal)
{
// Calculate the total monetary amount
markUpTotal = costPrice * markUpRate;
}
and then jumps directly to the Message.Show(..) line.
There is a lot of crossover in you if else statements. If costPrice is 50, do you want to run rate A, rate B, or rate C (I think you have put your > sign the wrong way with markup rate C).
Also, why is it in a try loop? You are basically saying: "If there are no problems, assign costPrice to whatever the user entered, then skip the rest. And if there is a problem, do the rest but the costPrice will be the default value I assigned it to at the start (0)."
Basically, all the rest of the stuff should be in the try loop, not the catch loop.
Oh and read Xaero's answer as well, I have to wite this here though because i'm not allowed not comment yet :(.
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 8 years ago.
Improve this question
I am trying to initialize 3 different methods and getting the error.
this variable does not exist in the current context
I'm thinking its because of scope but I don't see how I can change the calculatebmi() or calculateextime() methods without messing them up.
How do I get rid of this error? It is complaining about oldbmi, time, and newbmi.
Related Code:
public partial class Program2 : Form
{
private double _height;
private double _weight;
const int caloriesBurned = 10000;
const int walkingSpeed = 4;
const double fatCaloriesPerPound = 3500;
const double metricWalkingSpeed = walkingSpeed / .62137;
private double calculateBmi(double metricWeight, double metricHeight)
{
double oldBmi = metricWeight / Math.Pow(metricHeight, 2);
double newMetricWeight = metricWeight - (caloriesBurned / (fatCaloriesPerPound * 2.2046));
double newBmi = newMetricWeight / Math.Pow(metricHeight, 2);
return oldBmi;
}
private double calculateExTime(double metricWeight, double metricHeight)
{
double exerciseMultiplier = .0215 * Math.Pow(metricWalkingSpeed, 3)
- .1765 * Math.Pow(metricWalkingSpeed, 2)
+ .8710 * metricWalkingSpeed
+ 1.4577;
double time = caloriesBurned / (exerciseMultiplier * metricWeight);
return time;
}
private void displayresults( double _height, double _weight, double oldbmi,double time, double newBmi )
{
double newWeight = _weight - (caloriesBurned / fatCaloriesPerPound);
int feet = (int)_height / 12;
int inches = (int)_height % 12;
HeightText.Text = string.Format("{0}ft {1}in", feet, inches);
Weight.Text = _weight.ToString();
OriginalBmi.Text = oldBmi.ToString("F2");
NewBmi.Text = newBmi.ToString("F2");
NewWeight.Text = newWeight.ToString("F2");
ExerciseTime.Text = string.Format("{0} hrs {1} min", (int)(time), (int)(time % 60));
}
displayresults(_height, _weight,oldBmi,time,newBmi);
The problem appears to be in your call to the displayresults method. You're referencing oldbmi, newbmi, and time there, but none of these objects exist in that scope, because they're defined locally to calculateBmi. This is an assumption on my part - you haven't really shown the context of the code in which you call calculateBmi - but it seems to be the case.
If you want the oldBmi and newBmi values you calculate in displayresults() to be usable elsewhere in the program, you need to create private fields or public properties at the class level, like you have for _height and _weight. Then you can set this.newbmi to the value you calculate, rather than creating a new double in that scope which never gets used.
So instead, the top of your class would look like this:
private double _height;
private double _weight;
private double oldbmi = 0;
private double newbmi = 0;
const int caloriesBurned = 10000;
const int walkingSpeed = 4;
const double fatCaloriesPerPound = 3500;
const double metricWalkingSpeed = walkingSpeed / .62137;
and your calculateBmi method would look like so:
private double calculateBmi(double metricWeight, double metricHeight)
{
this.oldBmi = metricWeight / Math.Pow(metricHeight, 2);
double newMetricWeight = metricWeight - (caloriesBurned / (fatCaloriesPerPound * 2.2046));
this.newBmi = newMetricWeight / Math.Pow(metricHeight, 2);
return oldBmi;
}
and you can call displayresults with this.oldbmi and this.newbmi.
You should know that nearly everything in your code is against the .NET naming conventions. Variables shouldn't begin with '_', consts should be CamelCase, private fields should be pascalCase, and methods should always be CamelCase. Please take a look through this: http://msdn.microsoft.com/en-us/library/vstudio/618ayhy6%28v=vs.100%29.aspx. Many people here follow these conventions and it'll make it easier for you to get help in the future.
You are calling a method displayresults which takes some parameters.
Whenever you call a method you need to pass values a/c to the DataType of the method's parameters. It is not necessary to pass the variables with exact names as the method has (I think you have a confusion with that).
So the right syntax will be like:
displayresults(10, 20, 30, 40, 50);
OR
If you want to pass variables you should have them in the current context:
double _height = 10;
double _weight = 20;
double oldBmi = 30;
double time = 40;
double newBmi = 50;
displayresults(_height, _weight, oldBmi, time, newBmi);