Carpark calculation - c#

What I am attempting is, if hours are more than 8 charge the maximum fee, otherwise calculate the product of hours and the hourly rate. The hours must be rounded up. Eg if they enter 2.3 or 2.9 it needs to be rounded to 3.
It's pretty simple I know but Visual Studio says parkTime is a variable but used like a method and I'm stuck. Still a noob at C#.
In detail: The parking fee in a parking station is calculated on the whole number of hours (rounded up) multiplied by the hourly rate of $2.50. The maximum parking fee is $20.00, e.g. parking for 4 hours yields a fee of $10.00, and parking for 10 hours yields a parking fee of $20.00 (i.e. the maximum fee).
My program is required to take hours input by keyboard and output the parking fee to the screen.
Note: Use ‘named constants’ rather than variables or literals for fixed amounts e.g.
const decimal HOURLY_RATE = 2.50;
const decimal MAX_FEE = 20.00;
class Program
{
static void Main(string[] args)
{
decimal parkTime; // input - time in hour eg 1.5 for 1 and hour hours
const decimal HOURLY_RATE = 2.50m;
const decimal MAX_FEE = 20.00m;
decimal parkFee;
Console.WriteLine("Time parked in hours: Eg 1.5 or 2.75");
parkTime = decimal.Parse(Console.ReadLine());
if (parkTime > 8)
{
Console.Write("Total fee is $" + MAX_FEE);
}
else
{
parkFee = parkTime (Math.Ceiling) * HOURLY_RATE;
Console.Write("Parking Fee = $" + parkFee);
}
Console.ReadKey(); // pause (before program ends)
}
}

You got the order wrong. It should be Math.Ceiling(parkTime)

It is a simple syntax error. What should parkTime (Math.Ceiling) do? You want Math.Ceiling(parkTime) * HOURLY_RATE.
BTW: You could further simplify your code by using Math.Min:
parkTime = decimal.Parse(Console.ReadLine());
parkFee = Math.Min(8, Math.Ceiling(parkTime)) * HOURLY_RATE;
Since your MAX_FEE is equal to 8 * HOURLY_RATE.

Does your code even compile? asking cause of this line
parkTime (Math.Ceiling) * HOURLY_RATE;
shouldn't this be
Math.Ceiling(parkTime) * HOURLY_RATE;

Related

An interest calculation task I'm working on doesn't output the proper results

So I'm currently taking a C# fundamentals course as the entrance stage of a 6 month C# learning program. One of the tasks we have under the "Data Types and Variables" is an interest calculator.
The premise is such: You have a "deposit" that you write in the first line. The deposit has a 5% interest to it. The program needs to output the deposit's value for 3 years, for each year, all at once.
So 100.00, 105.00, 110.25, 115.76. The numbers after the decimal point need to be rounded to 2 digits, as well as "The rules of math for rounding apply here".
double deposit = double.Parse(Console.ReadLine());
double interest = (deposit*5)/100;
double yearOne = deposit + interest;
double yearTwo = yearOne + interest;
double yearThree = yearTwo + interest;
string totalSums = ($"{yearOne:N2}\n{yearTwo:N2}\n{yearThree:N2}\n");
Console.WriteLine( totalSums );
This is the code I've written so far. It SEEMS to work, but it's not as accepted.
If I put the deposit value as 100 (one of the examples), I get this output:
100
105.00
110.00
115.00
I've put the calculation for the interest percentage as double interest = (deposit*5)/100, which checks out if I use an external calculator to test it. But the program doesn't give the right output.
Say if I put 100.23 as the deposit input, I'll get: 105.24, 110.25, 115.26 when I should get 105.24, 110.50, 116.02. However, a round 100.00 doesn't even display the digits after the decimal point, just rounds them down to the whole number.
I thought the problem comes from using double and not decimal due to floating-point precision issues, so I changed everything to decimal. I still get this exact problem. Nothing changes.
I've had other issues that I at least have ideas on where I'm going wrong, but this one has been screwing with me since 3 days. So I resorted to some help here.
Why am I not getting the correct outputs ? Where is my problem coming from ? Is it the math ? Or logic ? Maybe I'm not using the correct method ? I'm at a loss... And the learning resources I've been given don't seem to help me with this issue, too. Like it's the ONLY task that the resources don't help with.
I've also seen other posts about compound interest, but they use arrays and other things that I'm not yet at the point of learning within the program. So code like that isn't gonna pass the automatic tester. I'm not asking for a complete code solving or "cheat" if you will; I just need some guidance on what my issue here is, because I'm clueless at this point.
Your question is about compound interest, not simple interest. Therefore, you need to calculate the new interest every year.
double deposit = double.Parse(Console.ReadLine());
double yearOne = deposit + (deposit * 5)/100;
double yearTwo = yearOne + (yearOne * 5)/100;
double yearThree = yearTwo + (yearTwo * 5)/100;
string totalSums = ($"{yearOne:N2}\n{yearTwo:N2}\n{yearThree:N2}\n");
Console.WriteLine( totalSums );
If you know about loops, you can create a loop over 3 years and update the amount in the account:
static class Program
{
static void Main(string[] args)
{
// set interest rate (fixed)
decimal rate = 5m/100;
// get deposit amount from user
Console.WriteLine("Enter Initial Amount:");
string input = Console.ReadLine();
decimal amount = decimal.Parse(input);
// loop over three years
Console.WriteLine($"{"year"}\t{"amount"}");
for (int year = 1; year <= 3; year++)
{
// calculate interest for the year based on
// current amount in the account
decimal interest = rate * amount;
// deposit interest in account
amount += interest;
Console.WriteLine($"{year}\t{amount:c2}");
}
}
}
with output
Enter Initial Amount:
1000
year amount
1 $1,050.00
2 $1,102.50
3 $1,157.63
you need to recalculate the interest amount each year.
double deposit = double.Parse(Console.ReadLine());
//Use deposit to calculate interest
double yearOneinterest = (deposit*5)/100;
double yearOne = deposit + yearOneinterest;
//Use yearOne amount to calculate interest
double yearTwointerest = (yearOne*5)/100;
double yearTwo = yearOne + yearTwointerest;
//Use yearTwo amount to calculate interest
double yearThreeinterest = (yearTwointerest*5)/100;
double yearThree = yearTwo + yearThreeinterest;
string totalSums = ($"{yearOne:N2}\n{yearTwo:N2}\n{yearThree:N2}\n");
Console.WriteLine( totalSums );

Using Exponents with Decimals [duplicate]

This question already has answers here:
Is there a Math API for Pow(decimal, decimal)
(6 answers)
Closed 7 years ago.
i am still new to learning C# and was wondering if i could get some help. I am writing a program C# and Windows forms so that users can calculate their monthly payments and interest for a mortgage. The equation i have for the payments is:
Payment = p * r / ( 1 - ( 1 + r ) ^ ( -n ) )
Where p is the amount of the loan, r is the monthly interest rate given as a number from 0 (for 0 percent) and 1 (for 100 percent), n is the duration of the loan in months
Then the formula for the total interest paid is: total interest = n * payment –p
Now i have tried entering all of these numbers as doubles using the Math.Pow method for the payments and got incorrect calculations. I am assuming that the rate NEEDS to be a decimal, so when i try them ALL as decimals, VS doesnt like the "^" method or the math.pow method. So my question is, how are you supposed to use decimals with exponents?
For those that wish to see my current code please note that i am just trying to get the calculations finished before i start adding extra 'else' statements.
decimal amnt = Convert.ToDecimal(txtAMNT.Text);
string Amount=Convert.ToString(txtAMNT.Text);
decimal rate = Convert.ToDecimal(txtRATE.Text);
string Rate = Convert.ToString(txtRATE.Text);
decimal time = Convert.ToDecimal(txtTIME.Text);
string Time=Convert.ToString(txtTIME.Text);
decimal monthpay;
decimal totalinterest;
decimal realrate = rate / 100;
if ((Amount == "")||(Rate == "")||(Time==""))
{
MessageBox.Show("Please fill all boxes with numbers");
}
else
{
monthpay=amnt*realrate/(1-(1+realrate)^(-time));
totalinterest=time*monthpay-amnt;
mtbMonPay.Text=monthpay.ToString("c");
mtbTotalInterest.Text=totalinterest.ToString("c");
}
You should use double for this calculation.
The reason you got incorrect results was that you forgot to divide the annual interest rate by 12 to get the monthly interest rate.
Decimal does not support exponentiation. Also, the caret operator (^) is not for exponentiation in C#; there is no exponentiation operator. You just have to call Math.Pow.
See also https://stackoverflow.com/a/6426826/385844
double should be plenty accurate for the precisions you are working with. Try changing all your decimals to doubles.
Another problem is your rate. Real rate is entered value/100, which means 1 which you said meant 100% actually ends up as 1%.

Transform minutes into hours [duplicate]

This question already has answers here:
Allow only numbers to be inserted & transform hours to minutes to calculate gold/min - UPDATED
(2 answers)
Closed 9 years ago.
I've got stuck in my program, i need to calculate the gold/minute but my math formula won't do the desire thing. As I input the hours into a float(something like 1.2 hours) the transformation will be 72 min instead of 80 as I need.
Can you please help me ? I marked in comment below where the problem is.
And here is my code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace YourGold
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Welcome to YourGold App! \n------------------------");
Console.WriteLine("Inesrt your gold: ");
int gold = int.Parse(Console.ReadLine());
Console.WriteLine("Your gold is : " + gold);
Console.WriteLine("Inesrt your time(In Hours) played: ");
float hours = float.Parse(Console.ReadLine());
int minutes = 60;
float time = (float)hours * minutes; // Here the calculation are wrong...
Console.WriteLine("Your total time playd is : " + time + " minutes");
float goldMin = gold / time;
Console.WriteLine("Your gold per minute is : " + goldMin);
Console.WriteLine("The application has ended, press any key to end this app. \nThank you for using it.");
Console.ReadLine();
}
}
}
Thanks a lot.
P.S it's related to this question:Allow only numbers to be inserted & transform hours to minutes to calculate gold/min - UPDATED , I update it same as this but i think i should have done a new question as i did now(I'm still learning how to go on with this platform:) )
Use the built-in TimeSpan:
TimeSpan time = TimeSpan.FromHours(1.2);
double minutes = time.TotalMinutes;
TimeSpan.FromHours Method Returns a TimeSpan that represents a specified number of hours, where the specification is accurate to the nearest millisecond.
You can also do:
// string timeAsString = "1:20";
TimeSpan time;
if (TimeSpan.TryParse(timeAsString, CultureInfo.InvariantCulture, out time))
{
double minutes = time.TotalMinutes;
//... continue
}
else
{
// Ask user to input time in correct format
}
Or:
var time = new TimeSpan(0, 1, 20, 0);
double minutes = time.TotalMinutes;
If you really want your program to behave as you want do this.
time = (int)hours * 60 + (hours%1)*100
var minutes = TimeSpan.FromHours(1.2).TotalMinutes; // returns 72.0
var hours = 1.2;
var minutes = ((int)hours) * 60 + (hours%1)*100;
And a side note: such way of inputting time is IMO not a good one. It'll be confusing and I guess that more often than not people will be actually entering 1:20 instead of 1.2, which'll break your application. And if not, they might be entering 1.5 thinking of 90 minutes. I know I would have done it like that.

Using integer instead of decimal

I'm having trouble with a particular homework assignment of mine. It almost seems impossible. The question goes like this...
"In the future, you may work with other programming languages that do not have a type like decimal which supports precise monetary calculations. In those languages, you should perform such calculations using integers. Modify the application to use only integers to calculate the compound interest. Treat all monetary amounts as integral numbers of pennies. Then break the result into its dollars and cents portions by using the division and remainder operations, respectively. Insert a period between the dollars and the cents portions when you display the results."
When I follow the directions and use integers I get these overflow errors before I can even divide anything out. Does anyone have any idea how to make this work? Here's the original code that needs to be modified...
decimal amount; //amount on deposit at end of each year
decimal principal = 1000; //initial amount before interest
double rate = 0.05; //interest rate
//display headers
Console.WriteLine("Year{0,20}", "Amount on deposit");
//calculate amount on deposit for each of ten years
for (int year = 1; year <= 10; year++)
{
//calculate new amount for specified year
amount = principal *
((decimal)Math.Pow(1.0 + rate, year));
//display the year and the amount
Console.WriteLine("{0,4}{1,20:C}", year, amount);
}
This is the code I have so far...
long amount; //amount on deposit at end of each year
long principal = 100000; //initial amount before interest
long rate = 5; //interest rate
long number = 100;
//display headers
Console.WriteLine("Year{0,20}", "Amount on deposit");
//calculate amount on deposit for each of ten years
for (int year = 1; year <= 10; year++)
{
//calculate new amount for specified year
amount = principal *
((long)Math.Pow(100 + rate, year));
amount /= number;
number *= 10;
//display the year and the amount
Console.WriteLine("{0,4}{1,20}", year, amount);
It gets some of the right numbers, but then starts spitting out negative numbers for some reason.
Just to give you a hint:
int amount;
//...some code...
//let's pretend we have an amount of 100.97
amount = (int)(100.97 * 100); // amount = 10097
Math.Pow uses double. It does not use long.
In the following line you are implictly casting your rate and year to double.
amount = principal *
((long)Math.Pow(100 + rate, year));
So you are effectly doing this:
double dRate = (double)(100 + rate);
double dYear = (double)year;
double dPow = Math.Pow(dRate, dYear);
amount = principal * (long)dPow;
If you want your Pow function to really use long then you probably need to write it yourself.

Decimals to Integers [duplicate]

This question already has answers here:
Using integer instead of decimal
(2 answers)
Closed 9 years ago.
I'm having trouble with a particular homework assignment of mine. It almost seems impossible. The question goes like this...
"In the future, you may work with other programming languages that do not have a type like decimal which supports precise monetary calculations. In those languages, you should perform such calculations using integers. Modify the application to use only integers to calculate the compound interest. Treat all monetary amounts as integral numbers of pennies. Then break the result into its dollars and cents portions by using the division and remainder operations, respectively. Insert a period between the dollars and the cents portions when you display the results."
When I follow the directions and use integers I get these overflow errors before I can even divide anything out. Does anyone have any idea how to make this work? Here's the original code that needs to be modified...
decimal amount; //amount on deposit at end of each year
decimal principal = 1000; //initial amount before interest
double rate = 0.05; //interest rate
//display headers
Console.WriteLine("Year{0,20}", "Amount on deposit");
//calculate amount on deposit for each of ten years
for (int year = 1; year <= 10; year++)
{
//calculate new amount for specified year
amount = principal *
((decimal)Math.Pow(1.0 + rate, year));
//display the year and the amount
Console.WriteLine("{0,4}{1,20:C}", year, amount);
}
This is the code I have so far...
ulong amount; //amount on deposit at end of each year
ulong principal = 100000; //initial amount before interest
ulong rate = 5; //interest rate
ulong number = 100;
//display headers
Console.WriteLine("Year{0,20}", "Amount on deposit");
//calculate amount on deposit for each of ten years
for (int year = 1; year <= 10; year++)
{
//calculate new amount for specified year
amount = principal *
((ulong)Math.Pow(100 + rate, year));
amount /= number;
number *= 10;
//display the year and the amount
Console.WriteLine("{0,4}{1,20}", year, amount);
It gets some of the right numbers, but then starts spitting out zeros for some reason.
You are changing the values of amount and number each time through the loop, but I don't believe that's what you want to do here. If you remove those assignments and change the parameters in your final Console.WriteLine call, (amount / 100 and amount % 100 will be helpful here) you should be able to get the result you are looking for.
((ulong)Math.Pow(100 + rate, year)) Will grow way too fast 105^10 > ulong.
I think teacher ment for them to keep math.pow as a decimal.
amount = (ulong)(Math.Round(principal *
Math.Pow((number + rate)/100.0, year),0));
//display the year and the amount
Console.WriteLine("{0,4}{1,17}.{2,-2}", year, "$" + (ulong)(amount / number), (ulong)(amount % number));
Question just says variables, not constants :) variables would all still be ulong

Categories

Resources