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]
Related
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;
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.
Background:
We have an embedded system that converts linear positions (0 mm - 40 mm) from a potentiometer voltage to its digital value using a 10-bit analog to digital converter.
------------------------
0mm | | 40 mm
------------------------
We show the user the linear position at 1 mm increments. Ex. 1mm, 2mm, 3mm, etc.
The problem:
Our system can be used in electromagnetically noisy environments which can cause the linear position to "flicker" due to noise entering the ADC. For example, we will see values like: 39,40,39,40,39,38,40 etc. when the potentiometer is at 39 mm.
Since we are rounding to every 1 mm, we will see flicker between 1 and 2 if the value toggles between 1.4 and 1.6 mm for example.
Proposed software solution:
Assuming we can not change the hardware, I would like to add some hysteresis to the rounding of values to avoid this flicker. Such that:
If the value is currently at 1mm, it can only go to 2mm iff the raw value is 1.8 or higher.
Likewise, if the current value is 1mm it can only go to 0mm iff the raw value is 0.2 or lower.
I wrote the following simple app to test my solution. Please let me know if I am on the right track, or if you have any advice.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PDFSHysteresis
{
class Program
{
static void Main(string[] args)
{
double test = 0;
int curr = 0;
Random random = new Random();
for (double i = 0; i < 100; i++)
{
test = test + random.Next(-1, 2) + Math.Round((random.NextDouble()), 3);
curr = HystRound(test, curr, 0.2);
Console.WriteLine("{0:00.000} - {1}", test, curr);
}
Console.ReadLine();
}
static int HystRound(double test, int curr, double margin)
{
if (test > curr + 1 - margin && test < curr + 2 - margin)
{
return curr + 1;
}
else if (test < curr - 1 + margin && test > curr - 2 + margin)
{
return curr - 1;
}
else if (test >= curr - 1 + margin && test <= curr + 1 - margin)
{
return curr;
}
else
{
return HystRound(test, (int)Math.Floor(test), margin);
}
}
}
}
Sample output:
Raw HystRound
====== =========
00.847 1
00.406 1
01.865 2
01.521 2
02.802 3
02.909 3
02.720 3
04.505 4
06.373 6
06.672 6
08.444 8
09.129 9
10.870 11
10.539 11
12.125 12
13.622 13
13.598 13
14.141 14
16.023 16
16.613 16
How about using the average of readings for the last N seconds, where N could be fairly small / sub-second depending on your sample rate?
You can use a simple linear average, or something more complex, depending on your needs. Several moving average algorithms are detailed on Wikipedia:
http://en.wikipedia.org/wiki/Moving_average
Depending on your sensitivity / responsiveness needs, you could reset the average if a new reading exceeds the running average by X%.
I had to deal with something similar sometime ago where I had to read voltage output from a circuit and display a graph on a computer screen. The bottom line is, this really depends on your system requirements. If the requirement is "1mm" accuracy then there is nothing you could really do. Otherwise, as mentioned above, you could go with several methods that can help you out lessen the flickering. You can:
Calculate the average of these values over a certain period of time the user can configure.
Allow the user to set a "Sensitivity threshold". This threshold can be used to decide on weather to consider the new value as valid or not. In your example, the threshold can be set to 2mm in which case values such as 39, 40, 39, 38 would read as 39mm
Also, have you thought about putting an external stabilizer between your application and the hardware itself?
I think Gareth Rees gave an excellent answer to a very similar question:
how to prevent series of integers to have the same value to often