Question

the number of seconds is shown negative when the stopwatch works for about 15 minutes and on.

Dim timeTook As Stopwatch = Stopwatch.StartNew

'Some time-consuming tasks

timeTook.Stop()

Dim mins As Long = CLng(timeTook.Elapsed.TotalMinutes.ToString) \ 1
Dim secs As Long = CLng(timeTook.Elapsed.TotalSeconds.ToString) \ 1 - 60 * mins
Label3.Text = "Time took: " & mins & " Minutes and " & secs & " Seconds"

This is maybe something about the timer or a logic error, but it looks logic to me. I can't figure out what does not work, please help.

Était-ce utile?

La solution

It would be much more readable and efficient if you just did it like this:

Dim timeTook As Stopwatch = Stopwatch.StartNew
'Some time-consuming tasks
timeTook.Stop()
Label3.Text = "Time took: " & Math.Floor(timeTook.Elapsed.TotalMinutes).ToString() & " Minutes and " & timeTook.Elapsed.Seconds.ToString() & " Seconds"

Or better yet:

Label3.Text = "Time took: " & timeTook.Elapsed.ToString()

The Elapsed property already has all the information you need, so it's silly, and more error prone, for you to recalculate it all yourself.

Autres conseils

The problem here is that the CLng() function rounds a floating point value. So if the elapsed time is, say, 0.6 minutes then you'll get mins = 1. Your secs value is now going to be negative.

You need to truncate the value so it is always rounded down. Let's get rid of the string conversion as well, that doesn't make sense:

Dim mins = Math.Truncate(timeTook.Elapsed.TotalMinutes)
Dim secs = timeTook.Elapsed.TotalSeconds - 60 * mins
Label3.Text = String.Format("Time took: {0:N0} minutes and {1:N0} seconds", _
                            mins, secs)

I'll leave the pluralization bug up to you to fix :)

Are you sure it is the minutes that is negative not seconds? Your code

Dim secs As Long = CLng(timeTook.Elapsed.TotalSeconds.ToString) \ 1 - 60 * mins

will always return negative because any number / negative number is negative.

Better way

Dim secs As Long = timeTook.Elapsed.TotalSeconds mod 60

Why not use .ToString with format?

    Label3.text = timeTook.Elapsed.ToString("hh\:mm\:ss")
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top