Okay first off, I'm pretty sure I'm not expected to use TimeSpan for this assignment; rather a formula series which shows the seconds, minutes, and hours in a message box when the user enters the number of seconds in the text box.
Here's where I'm stuck. We're supposed to check our answers with the example: 7565 seconds is 2 hours, 6 minutes, and 5 seconds. However, my code ends up calculating it as 2 hours, 6 minutes, and 6 seconds. It also keeps that answer when the initial number is 7560 seconds. I'm so confused!! It's a conditional scenario, in which the message box shows only the seconds if the user enters under 60 seconds, only minutes + seconds if the user enters between 60 and 3600 seconds, and hours + minutes + seconds if over 3600 seconds is entered. Here is what I have so far, and I'd appreciate any insight as to why my calculation is off :)
Thanks for the answers! But the 7565 isn't a constant; the user can enter any amount of seconds but my professor used 7565 as an example to check if we're on the right track.
private void calculateButton1_Click(object sender, EventArgs e)
{
int totalSeconds, hours, minutes, minutesRemainder, hoursRemainderMinutes, hoursRemainderSeconds;
totalSeconds = int.Parse(secondsTextBox1.Text);
minutes = totalSeconds / 60;
minutesRemainder = totalSeconds % 60;
hours = minutes / 60;
hoursRemainderMinutes = minutes % 60;
hoursRemainderSeconds = hoursRemainderMinutes % 60;
if (totalSeconds < 60)
{
MessageBox.Show(totalSeconds.ToString());
}
else if (totalSeconds < 3600)
{
MessageBox.Show(minutes.ToString() + " minutes, " + minutesRemainder.ToString() + " seconds");
}
else if (totalSeconds>3600)
{
MessageBox.Show(hours.ToString() + " hours, " + hoursRemainderMinutes.ToString() + " minutes, " + hoursRemainderSeconds.ToString() + " seconds");
}
}
Try using modular arithmetics
int totalSeconds = 7565;
int hours = totalSeconds / 3600;
int minutes = (totalSeconds % 3600) / 60;
int seconds = (totalSeconds % 60);
...
if (hours > 0)
MessageBox.Show(String.Format("{0} hours, {1} minutes, {2} seconds", hours, minutes, seconds));
else if (minutes > 0)
MessageBox.Show(String.Format("{0} minutes, {1} seconds", minutes, seconds));
else
MessageBox.Show(String.Format("{0} seconds", seconds));
来源:https://stackoverflow.com/questions/25802333/c-sharp-seconds-to-minutes-to-hours-conversion