I'm attempting to convert MPH into minute miles. I'm currently running code to do this by doing 60 / the miles per hour which gives me the result in minute miles.
For example 60/8mph = 7.5
However the answer I get I need to convert into minutes and seconds so that I would have 7 minutes 30 seconds. Is there a way I can get the numbers after the decimal point so I can multiply it by 60 to convert it to seconds, then add it back to the minutes.
You can use remainder,
double remainder = fmod(a_double, another_double);
should include <math.h>
Well, I don't know whether there is an existing class that handles this, but to answer your specific question, the fractional part of the decimal (mantissa?) would be:
((60 % 8) / 8.0f)
You can multiply that by 60.
Do it in seconds...
3600/8 = 450
450/60 = 7 remainder 30
= 7:30
It's pretty simple, you're on the right path actually.
What you need to do is:
Get Minutes
Get Seconds
Convert seconds from int to real time (0.5 to 30, etc..)
Add seconds to minutes
Get minutes by casting it to an Integer:
int minutes = 60/8;
Get seconds by using the remainder:
float seconds = 60%8;
Convert seconds to real time:
int realSeconds = seconds * 60;
Now get result back by adding both:
int totalSeconds = minuts + realSeconds;
Here's a little function that does it (typed directly to browser, probably won't compile)
#include <math.h>
int getMinuteMiles(float mph){
int minutes = 60/mph;
double seconds = fmod(60, mph);
int realSeconds = seconds * 60;
return minutes+realSeconds;
}
Related
I have Hours / Minutes / Seconds that I would like converted into an integer
7 Hours 30 Minutes 5 Seconds
You could use split():
import Foundation
func getSecondsFromString(timeString: String) -> (Int) {
let timeParts = timeString.replacingOccurrences(of: "[^0-9]", with: " ", options: [.regularExpression])
.split(separator: " ")
.map{Int($0)!}
return timeParts[0] * 3600 + timeParts[1] * 60 + timeParts[2]
}
print(getSecondsFromString(timeString: "7 Hours 30 Minutes 5 Seconds"))
Output:
27005
If you have the time difference between two dates in seconds using timeIntervalSince then you can directly convert this into hours as a double by doing
let hours: Double = elapsedTime / 3600 // 7.501388...
In your examples this is 7.5 which you can then multiply with the hourly rate. If you for some reason only want to use full hours you can either round to the nearest full hour
let fullHours = round(hours) // 8.0
or if you want to truncate minutes and keep the hour then you can do a integer division from the start
let hours: Int = elapsedTime / 3600 // 7
I have the following function:
function timestamp(duration)
local hours = duration / 3600
local minutes = duration % 3600 / 60
local seconds = duration % 60
return string.format("%02d:%02d:%02.03f", hours, minutes, seconds)
end
when the duration is 4.404 sec it returns 00:00:4.404
what is am looking for is 00:00:04.404
It should be:
string.format("%02d:%02d:%06.3f", hours, minutes, seconds)
Field width contains all characters of the number, including point and fraction.
The task is to Write a method that will take in a number of minutes, and returns a string that formats the number into hours:minutes.
here's what I have so far:
def time_conversion(minutes)
minutes = (minutes / 60) % 60
hours = minutes / (60 * 60)
format(" %02d:%02d ", hours, minutes)
return format
end
it's not working out for me
Try this
def time_conversion(time)
minutes = time % 60
hours = time / 60
minutes = (minutes < 10)? "0" + minutes.to_s : minutes.to_s
return hours.to_s + ":" + minutes
end
Using division in Ruby returns a whole number, lowered to the previous number. Using modulus returns the remainder after division.
Ruby's Numeric#divmod is exactly what you want here. It returns both the quotient and remainder of a division operation, so e.g. 66.divmod(60) returns [ 1, 6 ]. Combined with sprintf (or String#%, it makes for an extremely simple solution:
def time_conversion(minutes)
"%02d:%02d" % minutes.divmod(60)
end
puts time_conversion(192)
# => 03:12
Well try
h = minutes/60
M = minutes%60
I want to store duration of time in a Double and need to extract high and low values of Double (hour and minute) for accessing them. I also need to be able to set Double with two Ints (hour and minute).And I got something here now:
extension Double {
func hour() -> Int {
return NSNumber(double: floor(self)).integerValue
}
func minute() -> Int {
return NSNumber(float: Float(Double((self - floor(self)) * 100))).integerValue
}
init(hour: Int, minute: Int) {
self = Double(hour) + ( Double(minute) / 100 )
}
}
And then I've performed some testing with this in my appDelegate's didFinishLaunchingWithOptions:
var time: Double = 18.30
NSLog("Time is \"%f\" - so hours is \"%d\" and minutes is \"%d\".", time, time.hour(), time.minute())
time = Double(hour: 10, minute: 1)
NSLog("Time is \"%f\" - so hours is \"%d\" and minutes is \"%d\".", time, time.hour(), time.minute())
time = Double(hour: 15, minute: 45)
NSLog("Time is \"%f\" - so hours is \"%d\" and minutes is \"%d\".", time, time.hour(), time.minute())
Now, this code works. One might wonder why I convert Double to Float in the minute() function. This is because of an unknown issue that I faced when using Doubles without converting them to Floats before converting these Floats to Ints. If minutes didn't end with 0, one minute was subtracted for unknown reasons.For example, 10:42 returned 10 hours and 41 minutes. But 10:30 was still 10 hours and 30 minutes.Also 10:00 was 10 hours and 0 minutes.
This routine that I posted here seems to be working, but I was just wondering, if I am as efficient as possible... There's more conversion here than what would be needed.So, any improvements?
And does someone know the reason for unknown issue with decremented minute I mentioned?
A binary floating point number such as Double or Float cannot represent the number 10.42 exactly, therefore
multiplying the fractional part by 100 and truncating the result might give 41.
With the conversion to Float you are just "hiding" the problem.
Here is a version that rounds instead of truncating, and is overall a bit simpler. I have adopted the notation of "minute" from your code,
even if it represents 1/100 of an hour and not 1/60.
extension Double {
func hour() -> Int {
return Int(self)
}
func minute() -> Int {
return Int(round(self * 100.0)) % 100
}
init(hour: Int, minute: Int) {
self = Double(hour) + ( Double(minute) / 100 )
}
}
Other possible approaches to solve your problem:
Store the duration as an integer representing the total
number of minutes. E.g. "10:42" would be stored as 10*60 + 42.
Then you have no rounding problems at all.
Use the Foundation
type NSDecimalNumber instead of Double, which can represent
a decimal integer with up to 38 digits exactly.
Trying to work out where I have screwed up with trying to create a count down timer which displays seconds and milliseconds. The idea is the timer displays the count down time to an NSString which updates a UILable.
The code I currently have is
-(void)timerRun {
if (self.timerPageView.startCountdown) {
NSLog(#"%i",self.timerPageView.xtime);
self.timerPageView.sec = self.timerPageView.sec - 1;
seconds = (self.timerPageView.sec % 60) % 60 ;
milliseconds = (self.timerPageView.sec % 60) % 1000;
NSString *timerOutput = [NSString stringWithFormat:#"%i:%i", seconds, milliseconds];
self.timerPageView.timerText.text = timerOutput;
if (self.timerPageView.resetTimer == YES) {
[self setTimer];
}
}
else {
}
}
-(void)setTimer{
if (self.timerPageView.xtime == 0) {
self.timerPageView.xtime = 60000;
}
self.timerPageView.sec = self.timerPageView.xtime;
self.timerPageView.countdownTimer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:#selector(timerRun) userInfo:Nil repeats:YES];
self.timerPageView.resetTimer = NO;
}
int seconds;
int milliseconds;
int minutes;
}
Anyone got any ideas what I am doing wrong?
You have a timer that will execute roughly 100 times per second (interval of 0.01).
You decrement a value by 1 each time. Therefore, your self.timerPageView.sec variable appears to be hundredths of a second.
To get the number of seconds, you need to divide this value by 100. To get the number of milliseconds, you need to multiply by 10 then modulo by 1000.
seconds = self.timerPageView.sec / 100;
milliseconds = (self.timerPageView.sec * 10) % 1000;
Update:
Also note that your timer is highly inaccurate. The timer will not repeat EXACTLY every hundredth of a second. It may only run 80 times per second or some other inexact rate.
A better approach would be to get the current time at the start. Then inside your timerRun method you get the current time again. Subtract the two numbers. This will give the actual elapsed time. Use this instead of decrementing a value each loop.
You set a time interval of 0.01, which is every 10 milliseconds, 0.001 is every millisecond.
Even so, NSTimer is not that accurate, you probably won't get it to work every 1 ms. It is fired from the run loop so there is latency and jitter.
These calculations look pretty suspect:
seconds = (self.timerPageView.sec % 60) % 60 ;
milliseconds = (self.timerPageView.sec % 60) % 1000;
You are using int type calculations (pretty sketchy in their implementation) on a float value for seconds.
NSUInteger seconds = (NSUInteger)(self.timerPageView.sec * 100); //convert to an int
NSUInteger milliseconds = (NSUInteger) ((self.timerPageView.sec - seconds)* 1000.);