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.
Related
So I am trying to finish an assignment which involves the user to enter the original video time as a floating point value then have the user enter the playback speed
factor, again as a floating point value. Then once I have this information I will need to convert the original time into seconds then, use the factor to determine what the new video time would be. Display the results in seconds. (Note that you must use an integer data type to store the new video time.) Now as I already have mass majority of this code already done I'm confused on when it comes to converting part of the code.
using System;
class Program
{
public static void Main(string[] args)
{
float og_videotime, playback_speed;
int og_videotime_seconds, new_videotime_seconds;
Console.WriteLine("[Fast-Forward]");
Console.Write("What is the original video time? ");
og_videotime = float.Parse(Console.ReadLine());
Console.Write("What is the playback speed factor? ");
playback_speed = float.Parse(Console.ReadLine());
// convert time to seconds
og_videotime_seconds = (int)(og_videotime * 60);
new_videotime_seconds = (int)(og_videotime_seconds / playback_speed);
// space
Console.WriteLine();
// output
Console.WriteLine("The new video time would be {0} second(s).", new_videotime_seconds);
Console.WriteLine("That saves you {0} second(s) from the original video speed.", og_videotime_seconds - new_videotime_seconds);
}
}
A sample output provided:
[Fast-Forward]
What is the original video time? 2.30
What is the playback speed factor? 2
The new video time would be 75 second(s).
That saves you 75 second(s) from the original video speed.
Another Sample output:
[Fast-Forward]
What is the original video time? 3.59
What is the playback speed factor? 1.75
The new video time would be 136 second(s).
That saves you 103 second(s) from the original video speed.
But my code produces:
[Fast-Forward]
What is the original video time? 3.59
What is the playback speed factor? 1.75
The new video time would be 122 second(s).
That saves you 93 second(s) from the original video speed.
Math for the first sample: Now when I do the exact same number both my new video time and save seconds come out to be 69 instead of 75 which is where my confusion comes in. If I am correct to receive 75 I would have to do 2 * 60 = 120 then 120 + 30 = 150 then 150 / 2 to get 75 but I don't understand how I can break this down.
Thank you for all the help!
The code you wrote looks like C. Predefining variables? Why?
I don't know why, but nobody is suggesting to use the TimeSpan class. It has support for arithmetic. It has a Parse method. It actually represents a timespan. It can output in seconds
You just have to feed it a correct time format. "hh:mm:ss"
Console.Write("What is the original video time? ");
var og_videotime = TimeSpan.Parse(Console.ReadLine());
Console.Write("What is the playback speed factor? ");
var playback_speed = double.Parse(Console.ReadLine());
var new_videotime = og_videotime / playback_speed;
Console.WriteLine($"The new video time would be {new_videotime.TotalSeconds:0.00} second(s).");
edit: IMHO using float would not be a C# way to go. But there are plenty bad professors around, so you might be stuck with learning to program the wrong way.
just edit this line:
You are multiplying 2.30 by 60 and the result is 138. Not 150
// og_videotime_seconds = (int)(og_videotime * 60);
var temp = og_videotime.ToString("N2").Split('.');
og_videotime_seconds = int.Parse(temp[0]) * 60 + int.Parse(temp[1]);
You can multiply the number part of og_videotime by 60 and add it to the decimal part.
You can use the following code:
I just made a small change
class Program
{
static void Main(string[] args)
{
float og_videotime, playback_speed;
int og_videotime_seconds, new_videotime_seconds;
Console.WriteLine("[Fast-Forward]");
Console.Write("What is the original video time? ");
og_videotime = float.Parse(Console.ReadLine());
Console.Write("What is the playback speed factor? ");
playback_speed = float.Parse(Console.ReadLine());
// convert time to seconds
var FloatToMin =og_videotime.ToString().Split('.');
og_videotime_seconds = (int.Parse(FloatToMin[0]) * 60) + int.Parse(FloatToMin[1]);
new_videotime_seconds = (int)(og_videotime_seconds / playback_speed);
// space
Console.WriteLine();
// output
Console.WriteLine("The new video time would be {0} second(s).", new_videotime_seconds);
Console.WriteLine("That saves you {0} second(s) from the original video speed.", og_videotime_seconds - new_videotime_seconds);
}
}
My mother says: the mountain that can be seen is not far away, don't stop trying
To go from a float value of 2.3 to 150 seconds, without extra string manipulation inbetween:
float og_videotime = 2.30f; // result of the "float.Parse"
int mins = (int)Math.Floor(og_videotime); // 2 [minutes]
int secpart = (int)Math.Round((og_videotime - mins) * 100); // 2.3 - 2 = 0.3; 0.3 * 100 = 30 [seconds]
int og_videotime_seconds = secpart + mins * 60; // 150 [seconds]
I'm creating a console application that checks if guy has beaten the record for climbing a mountain. There is a catch that says the guy loses 30 seconds every 50 meters i named this varible "wastedTime" and if its 26.5 seconds i want it to be calculated as 26 instead of 27 this is my code:
class Program
{
static void Main(string[] args)
{
double record = double.Parse(Console.ReadLine());
double range = double.Parse(Console.ReadLine());
double timeForOneMeter = double.Parse(Console.ReadLine());
double time = timeForOneMeter * range;
double wastedTime = Math.Truncate((range / 50) * 30);
double georgesTime = time + (wastedTime);
Console.WriteLine(wastedTime);
if (georgesTime<=record)
{
Console.WriteLine($"Yes! The new record is {georgesTime:f2} seconds.");
}
else if (georgesTime>record)
{
Console.WriteLine($"No! He was {georgesTime-record:f2} seconds slower.");
}
}
}
You can use Math.Floor method, documentation is here.
Returns the largest integral value less than or equal to the specified number.
For example:
Console.WriteLine(Math.Floor(26.99d));
// outputs: 26
C# Fiddle with example here.
I'm taken c# class and have to write a program. You burn 5 calories per minute when running on a treadmill. Write a program that uses a loop to display the number of calories burned after 20,35,45 minutes. I know I can use a while or for loop. But problem I have those you use step say of 5 or 10 but as you see 20,35,45 is step 15 then 10 how would I work that into while or for loop?
There are several ways to do this.
Create a for loop and step 5 and check if any matches the given minutes to display. But there are better ways.
I'd rather write something like:
// just make a variable and put the calories per minute in it.
// it's just more clear to read and if you need to use it multiple times,
// it avoids to put the value multiple times in your code.
var caloriesBurnedPerMinute = 5;
// this specifies an array of integers, (it detects that the values are integers.
var minutesToDisplay = new[] { 20, 25, 45 };
// make a loop over each value in the array
foreach(var minutes in minutesToDisplay)
{
// I'd rather don't put the calculations in the writeline, easier to debug.
var caloriesBurned = minutes * caloriesBurnedPerMinute;
// display the value.
Console.WriteLine($"Calories burned after {minutes} is {caloriesBurned}");
}
This way you don't need to write bruteforce loops, which just waste time/energy.
You can test this out by creating a console app and pasting the code in this method into it. It sets calories burned per minute to a constant value of 5. Then iterates through minutes on treadmill starting at 1 minute and ending at 45. After each minute 5 calories are burned and at the minutes specified in the switch statement, the number of calories burned are stored in a variable and displayed to the screen.
private static void Main(string[] args)
{
const int calsBurnedPerMinute = 5;
// i represents minutes between 1 and 45
for (var i = 1; i <= 45; i++)
{
var calsBurned = 0;
switch (i)
{
case 20:
calsBurned = calsBurnedPerMinute * i;
Console.WriteLine("Calories Burned After 20 minutes: " + calsBurned);
break;
case 35:
calsBurned = calsBurnedPerMinute * i;
Console.WriteLine("Calories Burned After 35 minutes: " + calsBurned);
break;
case 45:
calsBurned = calsBurnedPerMinute * i;
Console.WriteLine("Calories Burned After 45 minutes: " + calsBurned);
break;
}
}
Console.ReadKey();
}
Output:
Calories burned after 20 minutes: 100
Calories burned after 35 minutes: 175
Calories burned after 45 minutes: 225
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;
I need to calculate the time difference faken for division most accurately in nano seconds. Please tell me to do this.
At Present i'm using a lower accuracy method in which the problem is that : when the first calculation is performed it shows 87 milliseconds or 65 milliseconds as answer. But when the function is called again second time or more, it only show 0 milliseconds.
The code is :
long startTick = DateTime.Now.Ticks;
double result = (double)22 / 7;
result = System.Math.Round(result, digit);
long endTick = DateTime.Now.Ticks;
long tick = endTick - startTick;
double milliseconds = tick / TimeSpan.TicksPerMillisecond;
time.Text = result + "\nThe division took " + milliseconds + " milliseconds to complete.";
digit is the parameter of function which is variable. No matter what the value of digit is the milliseconds value remains 0 after first calling of function....
Please suggest more accurate way in which calling the same function with different decimal digits will result in different time interval in c# for windows Phone.
I think the memory flush should be done before and after each calculation. But i dont know how to do this.
I don't like this tick method personally for accuracy. I've tried stopwatch also but its not working. Please suggest another method best suited in my case. I want result like : 0.0345 or 0.0714 seconds.
Thanks
You are performing integer division on this line:
double milliseconds = tick / TimeSpan.TicksPerMillisecond;
Even though you are declaring it as a double, a long divided by a long will truncate the decimal. You are better off doing:
double milliseconds = (double)tick / TimeSpan.TicksPerMillisecond;
Or better yet, just ditch the tick stuff all together:
DateTime start = DateTime.Now;
double result = (double)22 / 7;
result = System.Math.Round(result, digit);
DateTime end = DateTime.Now;
double milliseconds = (end - start).TotalMilliseconds;
time.Text = result + "\nThe division took " + milliseconds + " milliseconds to complete.";
You won't be able to get micro or nano level precision, but you will get millisecond precision with a margin of error.
You still may get zero, however. You are trying to time how long a simple division operation takes. You could do millions of division operations in less than a second. You may want to do it 1,000,000 times, then divide the result by a 1,000,000:
DateTime start = DateTime.Now;
for (var i = 0; i < 1000000; i++)
{
double result = (double)22 / 7;
result = System.Math.Round(result, digit);
}
DateTime end = DateTime.Now;
double milliseconds = (end - start).TotalMilliseconds / 1000000;
This still won't be completely realistic, but should get you an actual number.
Since you have the time in ticks, just increase the resolution by multiplying the denominator:
double microseconds = tick / (TimeSpan.TicksPerMillisecond * 1000.0);
Why are you not using StopWatch Class to do your time calulation.
It is meant to the calculate the time the you want ..
Here is a link for your reference.
http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx
//if you want to get the full milliseconds you could also do something like this.
dateStartTime = Convert.ToDateTime(DateTime.Now.TimeOfDay.ToString());
//then where you end the code do this
dateEndTime = Convert.ToDateTime(DateTime.Now.TimeOfDay.ToString());
ddateDuration = (TimeSpan)(dateEndTime - dateStartTime);
then to display out what you are actually looking for in terms of miliseconds do
Console.WriteLine(ddateDuration.ToString().Substring(0, 8));
// or some other method that you are using to display the results