How to display result as a decimal - c#

Here is the homework problem:
Write a program that computes speed: Takes distance (in meters) and time (as three numbers: hours, minutes, seconds), computes speed, in meters per second, kilometres per hour and miles per hour (hint: 1 mile = 1609 meters). Prints results to Console.
Here is my code:
int distanceInMeters, hours, minutes, seconds;
Console.WriteLine("Please type distance in meters: ");
distanceInMeters = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please type time in hours: ");
hours = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please type time in minutes: ");
minutes = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please type time in seconds: ");
seconds = Convert.ToInt32(Console.ReadLine());
int metersSecond, kmH, milesH;
metersSecond = distanceInMeters / ((hours * 3600) + (minutes * 60) + seconds);
kmH = (distanceInMeters / 1000) / (hours + (minutes / 60) + (seconds / 3600));
milesH = (distanceInMeters / 1609) / (hours + (minutes / 60) + (seconds / 3600));
Console.WriteLine("Your speed in meters/seconds is: " + metersSecond);
Console.WriteLine("Please speed in km/h is: " + kmH);
Console.WriteLine("Please speed in miles/h is: " + milesH);

All of your variables in the following computation:
metersSecond = distanceInMeters / ((hours * 3600) + (minutes * 60) + seconds);
are of type int (whole number). Therefore the decimal places will be cut of. You can fix this by doing:
metersSecond = 1.0 * distanceInMeters / ((hours * 3600.0) + (minutes * 60.0) + seconds)
also metersSecond should be declared type double, float or decimal, those types support the decimal places you want.

Just cast any of the variables, say distanceInMeters to decimal and use decimal datatype for the output variables.
distanceInMeters = Decimal.Parse(Console.ReadLine());
Your output will automatically be in decimal format. You can round the digits if you want a certain level of precision.

Related

How do I show cents when I am writing a code to count total money, the code below is only showing a whole number (such as $1)

I am trying to write a code in C# that prints out the total of dollars and cents I have. I have the first part done, but the end of the code won't show how much cents there is when I run the whole code, it only shows a whole number (such as $1), when I need the code to show something like $1.56. What am I missing in the program in order to show this?
Console.WriteLine("Enter number of quarters: ");
int quarters = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter number of dimes: ");
int dimes = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter number of nickels: ");
int nickels = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter number of pennies: ");
int pennies = Convert.ToInt32(Console.ReadLine());
double dollars = (int)(((quarters * 0.25) + (dimes * 0.10) + (nickels * 0.05) + (pennies * 0.01)) % 1 * 100);
Console.WriteLine("Your total is $" + dollars);
When I typed in 4 quarters, 0 dimes, 0 nickels, and 1 penny, it shows the result as $1 not $1.01
You are forcing the result as int, so the decimals are cut
double dollars = (int)(((quarters * 0.25) + (dimes * 0.10) + (nickels * 0.05) + (pennies * 0.01)) % 1 * 100);
Do not force to int, on the contrary, force to double
double dollars = ((quarters * 0.25) + (dimes * 0.10) + (nickels * 0.05) + (pennies * 0.01)) % 1 * 100;
But, since you are handling money, I would recommend to handle everything with decimal
decimal dollars = ((quarters * 0.25) + (dimes * 0.10) + (nickels * 0.05) + (pennies * 0.01)) % 1 * 100;
Better explained in dotnet perls
Decimal accurately stores numeric data. The .NET Framework offers this
type for programs where rounding errors are harmful. Decimal stores
large and small numbers with many digits after the decimal place.
EDIT
When I put in decimal dollars instead of double dollars, I then get
the error, "Cannot implicitly convert type 'double' to 'decimal'. An
explicit conversion exists (are you missing a cast?)
It is becuse you need all the operation of the same type, you can do
int quarters =1;
int dimes = 1;
int nickels = 1;
int pennies = 1;
decimal dollars = ((quarters * 0.25m) + (dimes * 0.10m) + (nickels * 0.05m) + (pennies * 0.01m)) % 1 * 100;
Console.WriteLine("Your total is $" + dollars);
Note the use of a m after the number, this is to tell the compiler that the type is decimal or Money, not double.

How to repeat code if invalid data is entered

I need to make this code which calculates a Parking Fee give an error and ask the user to re-input the data if a false number is provided. For example if the user enters an amount that is less than 1 or greater than 24, an error code will appear and ask the user to re-enter a valid amount. Once a valid amount is entered I'd like it to output the parkFee.
I haven't updated my Pseudocode so apologies about that.
/* PSEUDOCODE */
/* HOURLY_RATE=2.5
* INPUT parkTime
* parkFee = HOURLY_RATE * hours
* OUTPUT parkFee */
decimal parkTime; // input - time in hour eg 1.5 for 1 and a half hours
const decimal HOURLY_RATE = 2.50m; // HOURLY_RATE * INPUT parkTime = parkFee
const decimal MAX_FEE = 20.00m; // MAX_FEE is set as a payment cap and ignores any extra charges incurred over 8 hours
decimal parkFee;
Console.WriteLine("ParkingFee1 program developed by: Ryley Copeman");
Console.WriteLine("Please enter your total time parked in hours: Eg 1.5 or 3.0");
parkTime = decimal.Parse(Console.ReadLine());
if (parkTime > 8)
{
Console.Write("Total fee is $" + MAX_FEE);
}
else
{
parkFee = Math.Ceiling(parkTime) * HOURLY_RATE;
Console.Write("Parking Fee = $" + parkFee);
}
while(parkTime < 0 || parkTime > 24) // validate...
//while (parkTime <= 0) )
{
Console.WriteLine("Error – Park Time out of range");
Console.WriteLine("Enter - Park Time between 0 and 24 (HOURS):");
parkTime = int.Parse(Console.ReadLine());
}
}
}
}
I think you just need this:
do
{
Console.WriteLine("Please enter your total time parked in hours: Eg 1.5 or 3.0");
parkTime = decimal.Parse(Console.ReadLine());
if (parkTime < 1 || parkTime > 24)
{
Console.WriteLine("Error – Park Time out of range");
}
}
while (parkTime < 1 || parkTime > 24);
if (parkTime > 8)
{
Console.Write("Total fee is $" + MAX_FEE);
}
else
{
parkFee = Math.Ceiling(parkTime) * HOURLY_RATE;
Console.Write("Parking Fee = $" + parkFee);
}
Note that you may want to adjust the code to always calculate the fee, and then apply the maximum:
parkFee = Math.Min(MAX_FEE, Math.Ceiling(parkTime) * HOURLY_RATE);
Console.Write("Parking Fee = $" + parkFee);
Here Math.Min will choose the smallest of the two values.
Finally, note that decimal.Parse will error if you enter something it doesn't expect (e.g. "1.2Hello", or ""), so it might be better to use TryParse:
bool isValidTime = false;
do
{
Console.WriteLine("Please enter your total time parked in hours: Eg 1.5 or 3.0");
bool parsedOK = decimal.TryParse(Console.ReadLine(), out parkTime);
isValidTime = parsedOK && parkTime >= 1 && parkTime <= 24;
if (!isValidTime)
{
Console.WriteLine("Error – Park Time out of range");
}
}
while (!isValidTime);
parkFee = Math.Min(MAX_FEE, Math.Ceiling(parkTime) * HOURLY_RATE);
Console.Write("Parking Fee = $" + parkFee);
Here the loops will continue until a valid value is entered. Note that in loop structures you can also use break; (leave the loop), and continue; (move to the next iteration of the loop) to control the flow.
As you already know about the concept of loops, there are a few possibilities, the simple one is a loop with break.
for (;;) {
// input
if (condition ok)
break;
// output "wrong, try again"
}
This will repeat the input as often as necessary and quit the loop once accaptable values are entered.
Console.WriteLine("ParkingFee1 program developed by: Ryley Copeman");
Console.WriteLine("Please enter your total time parked in hours: Eg 1.5 or 3.0");
parkTime = decimal.Parse(Console.ReadLine());
do
{
if(parkTime < 1 || parkTime > 24)
{
Console.WriteLine("Error – Park Time out of range");
Console.WriteLine("Enter - Park Time between 0 and 24 (HOURS):");
parkTime = decimal.Parse(Console.ReadLine());
continue;
}
if (parkTime > 8)
{
Console.Write("Total fee is $" + MAX_FEE);
}
else
{
parkFee = Math.Ceiling(parkTime) * HOURLY_RATE;
Console.Write("Parking Fee = $" + parkFee);
}
} while(parkTime < 1 || parkTime > 24);
/* PSEUDOCODE */
/* HOURLY_RATE=2.5
* INPUT parkTime
* parkFee = HOURLY_RATE * hours
* OUTPUT parkFee */
bool mustRepeat = true;
decimal parkTime = 0; // input - time in hour eg 1.5 for 1 and a half hours
const decimal HOURLY_RATE = 2.50m; // HOURLY_RATE * INPUT parkTime = parkFee
const decimal MAX_FEE = 20.00m; // MAX_FEE is set as a payment cap and ignores any extra charges incurred over 8 hours
decimal parkFee;
Console.WriteLine("ParkingFee1 program developed by: Ryley Copeman");
Console.WriteLine("Please enter your total time parked in hours: Eg 1.5 or 3.0");
while(mustRepeat) // validate...
{
parkTime = decimal.Parse(Console.ReadLine());
if(parkTime < 1 || parkTime > 24)
{
Console.WriteLine("Error – Park Time out of range");
Console.WriteLine("Enter - Park Time between 0 and 24 (HOURS):");
continue;
}
mustRepeat = false;
if (parkTime > 8)
{
Console.Write("Total fee is $" + MAX_FEE);
break;
}
else
{
parkFee = Math.Ceiling(parkTime) * HOURLY_RATE;
Console.Write("Parking Fee = $" + parkFee);
break;
}
}
}
}

Validate Value Between 1-24 In Parking Calculator

So i have an assignment where i need to validate that a number entered from the keyboard is between 1-24. The code for the calculator is below and is simple. It takes the value entered and multiplies it by 2.5 to a max of 20. I need to add code to make sure the number entered is between 1-24. Please Help. I think i need another if/else statement.
/* Harrison Currie
* 24/03
* Assignment Parking Fee 1
* Pseudocode
* HOURLY RATE = 2.50
* PARKING FEE = HOURS *Fee
* MAX FEE = 20.00
* OUTPUT TOTAL COST TO A MAX OF $20
* Validate Hours are between 1-24
*/
//Set Constants
const decimal HOURLY_RATE = 2.5m;
const decimal MAX_FEE = 20.00m;
//Declare Variables
decimal PARKING_FEE;
decimal HOURS;
//Input
//Enter HOURS as a decimal
PARKING_FEE = HOURS * HOURLY_RATE;
bool valid = false;
while (!valid)
{
Console.WriteLine("Enter Number Of Hours Parked");
HOURS = int.Parse(Console.ReadLine());
if (HOURS > 0 && HOURS <= 24)
{
valid = true;
}
else
{
Console.WriteLine("Hours must be between 1-24");
}
if (PARKING_FEE >= 20.00m)
{
PARKING_FEE = MAX_FEE;
}
else
{
PARKING_FEE = HOURS * HOURLY_RATE;
}
//Output
Console.WriteLine("Developed By Harrison Currie");
Console.WriteLine("The Cost Of Your Park Is $" + PARKING_FEE);
Console.Read();
Add while, and check, if entered is in range. And some info message for it.
something like that:
/* Harrison Currie
* 24/03
* Assignment Parking Fee 1
* Pseudocode
* HOURLY RATE = 2.50
* PARKING FEE = HOURS *Fee
* MAX FEE = 20.00
* OUTPUT TOTAL COST TO A MAX OF $20
* Validate Hours are between 1-24
*/
//Set Constants
const decimal HOURLY_RATE = 2.5m;
const decimal MAX_FEE = 20.00m;
//Declare Variables
decimal PARKING_FEE;
decimal HOURS =0;
//Input
bool valid = false;
while (!valid)
{
Console.WriteLine("Enter hours of parking: ");
bool parse = decimal.TryParse(Console.ReadLine(),out HOURS);
if (!parse)
{
Console.WriteLine("Not a number.");
continue;
}
if(HOURS > 0 && HOURS <= 24)
{
valid = true;
}
else
{
Console.WriteLine("Hours must be between 0-24");
}
}
PARKING_FEE = HOURS * HOURLY_RATE;
if (PARKING_FEE >= 20.00m) PARKING_FEE = MAX_FEE;
else PARKING_FEE = HOURS * HOURLY_RATE;
//Output
Console.WriteLine("Developed By Harrison Currie");
Console.WriteLine("The Cost Of Your Park Is $" + PARKING_FEE);
Console.Read();

How do I get this WHILE loop to work?

Currently doing an exercise that I thought I had done right, using an IF ELSE statement, but once submitted I was told instead to use a WHILE or DO-WHILE loop, and I'm having a bit of trouble. You'll see where I've used the WHILE loop, but it is giving me an infinite loop of the error message that I assigned to it and I don't know how to make it stop!
static void Main(string[] args)
{
decimal hours;
const decimal HOURLY_RATE = 2.5m;
const decimal MAX_FEE = 20.00m;
Console.WriteLine("Enter the amount of hours parked:");
hours = decimal.Parse(Console.ReadLine());
decimal parkingCost = hours * HOURLY_RATE;
while (hours < 1 || hours > 24)
{
Console.Write("Enter correct amount of hours - 1 to 24. ");
}
if (parkingCost > MAX_FEE)
{
Console.Write("Total fee is $" + MAX_FEE);
Console.WriteLine(" Time parked in hours is " + hours);
}
else
{
parkingCost = hours * HOURLY_RATE;
Console.WriteLine("The cost of parking is " + parkingCost.ToString("C"));
Console.WriteLine("Time parked in hours is " + hours);
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
}
So the idea is that I want for the "Enter correct amount of hours - 1 to 24. " to display if the user enters a number less than 1 or greater than 24, otherwise for the program to go ahead with the IF and ELSE statements.
Just add the line accepting input inside the while loop as shown below
static void Main(string[] args)
{
decimal hours;
const decimal HOURLY_RATE = 2.5m;
const decimal MAX_FEE = 20.00m;
Console.WriteLine("Enter the amount of hours parked:");
hours = decimal.Parse(Console.ReadLine());
decimal parkingCost = hours * HOURLY_RATE;
while (hours < 1 || hours > 24)
{
Console.Write("Enter correct amount of hours - 1 to 24. ");
hours = decimal.Parse(Console.ReadLine());
}
parkingCost = hours * HOURLY_RATE; // to recalculate
if (parkingCost > MAX_FEE)
{
Console.Write("Total fee is $" + MAX_FEE);
Console.WriteLine(" Time parked in hours is " + hours);
}
else
{
parkingCost = hours * HOURLY_RATE;
Console.WriteLine("The cost of parking is " + parkingCost.ToString("C"));
Console.WriteLine("Time parked in hours is " + hours);
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
}
You forgot to read the value in the while loop again to get a new value:
while (hours < 1 || hours > 24)
{
Console.Write("Enter correct amount of hours - 1 to 24. ");
Console.WriteLine("Enter the amount of hours parked:");
hours = decimal.Parse(Console.ReadLine());
}
Or as a Do While you can get rid of the first read and only loop on error
do {
Console.WriteLine("Enter the amount of hours parked:");
try{
hours = decimal.Parse(Console.ReadLine());
if(hours <1 || hours > 24)
Console.Write("Enter correct amount of hours - 1 to 24. ");
}
catch { Console.WriteLine("Please enter a valid numeric value"); }
} while(hours < 1 || hours > 24);
I added the try catch because if they enter a value that is not numeric it can throw an error.

More efficiënt way for reoccuring modulo?

I originally tried this with modulo but it did not work as expected
It keps giving me back the value(my teacher and I both couldn't figure it out)
Example:
Uw krijgt 200 x 2 euro terug
Uw Krijgt 100 x 1 euro terug
Uw krijgt 50 x 50 cent terug
Etc...
What it's supposed to do
I need to make a program that calculates howmuch change you get back.
Input 5
Cost: 2
Output: 1x 2 euro, 1x 1 euro, 0 x 50 cents, ...
My code
int Prijs, Ingegooid;
int Cent1, Cent2, Cent5, Cent10, Cent20, Cent50, Euro, Euro2, Wisselgeld;
private void btnCola_Click(object sender, RoutedEventArgs e)
{
Cent10 = 10;
Cent20 = 20;
Cent50 = 50;
Euro = 100;
Euro2 = 200;
Ingegooid = Convert.ToInt32(txbIngegooid.Text);
Prijs = 190;
Wisselgeld = (Ingegooid * 100 - Prijs);
Euro2 = Wisselgeld / Euro2;
MessageBox.Show("Uw krijgt " + Euro2 + " aantal 2 euro stukken terug.");
Euro = (Wisselgeld-Euro2*200) / Euro;
MessageBox.Show("Uw krijgt " + Euro + " aantal 1 euro stukken terug.");
Cent50 = (Wisselgeld-Euro2*200-Euro*100) / Cent50;
MessageBox.Show("Uw krijgt " + Cent50 + " aantal 50 cent stukken terug.");
Cent20 = (Wisselgeld-Euro2*200-Euro*100-Cent50*50) / Cent20;
MessageBox.Show("Uw krijgt " + Cent20 + " aantal 20 cent stukken terug.");
Cent10 = (Wisselgeld-Euro2*200-Euro*100-Cent50*50-Cent20*20) / Cent10;
}
You do not necessarily need modulo for this.
In this case it could actually be misleading.
Example: 90 Cents:
1 possible way to solve this:
1*50c + 2*20c.
Another way would be:
4*20c + 1*10c.
If you want to use the biggest coin whenever possible you could do it this way if you really want to:
10centAmmount = (change % 50) % 20;
In this case
10centAmmount = (90 % 50) % 20;
(90 % 50 = 40; 40 % 20 = 0 -> You do not need any 10 cent coins)
Working from the biggest coins to the smallest makes a lot more sense here.
I also recommend substracting the coins you already used from the change. Since the code gets "less crowded"
Euro2 = change/200;
change -= Euro2 * 200
Euro1 = change/100
change -= Euro1 * 100
...
A use case for modulo would be to figure out whether a number is dividable by any other number.
Example:
if (a % 4 == 0) {
print "a can be devided by 4";
Also the code is sort of confusing. You used Euro2 for the amount of cents a Euro coin has, but later you used it to count the number of 2 Euro coins. It would be a little less confusing if you used different variables for this. You could also use constants for values you never need to change, like the cent ammount of 2 euro coins.
Hope this sort of helps.

Categories