我一直在努力做一个简单的第二小时转换器来练习一些C#。奇怪的是,当我通过599秒标记时,程序减去60秒。所以,540秒等于9分钟; 599秒等于9分59秒,但600秒等于9分钟。我尝试使用按钮来触发命令而不是textchanged,按钮完成了工作。所以,我估计,问题的根源必须是textchanged事件本身。我将添加三个例子。截图图片是土耳其语,但您很容易理解。
我该如何解决这个问题,以及导致这个问题的原因是什么?这真是令人难以置信。
int second, minute, hour, minuteLeft, secondLeft;
private void txtTime_TextChanged(object sender, EventArgs e)
{
CalculateTime();
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
void CalculateTime()
{
if (txtTime.Text != "")
{
second = Convert.ToInt32(txtSure.Text);
secondLeft = second % 60;
second = second - minuteLeft;
minute = second / 60;
minuteLeft = minute % 60;
minute = minute - minuteLeft;
hour = minute / 60;
lblMsg.Text = hour.ToString() + " hours, " + minuteLeft.ToString() + " minutes " + secondLeft.ToString() + " seconds.";
}
else
{
lblMsg.Text = "";
}
答案 0 :(得分:0)
您要从秒数中减去minuteLeft
:
second = second - minuteLeft;
应该减去secondLeft值:
second = second - secondLeft;
答案 1 :(得分:0)
您可以考虑以不同的方式攻击问题:
var durationInSeconds = Convert.ToInt32(txtTime.Text);
var duration = new TimeSpan(0, 0, durationInSeconds);
var second = duration.Seconds;
var minute = duration.Minutes;
var hour = Convert.ToInt32(Math.Truncate(duration.TotalHours));
TimeSpan
非常适合此类问题,并且可以让您自动“#{提取持续时间的小时,分钟和秒组成部分。
你也可以考虑更换:
hour.ToString() + " hours, " + minuteLeft.ToString() + " minutes " + secondLeft.ToString() + " seconds.";
致电:
public static string ToPrettyFormat(TimeSpan timeSpan)
{
var dayParts = new[] { GetDays(timeSpan), GetHours(timeSpan), GetMinutes(timeSpan) }
.Where(s => !string.IsNullOrEmpty(s))
.ToArray();
var numberOfParts = dayParts.Length;
string result;
if (numberOfParts < 2)
result = dayParts.FirstOrDefault() ?? string.Empty;
else
result = string.Join(", ", dayParts, 0, numberOfParts - 1) + " and " + dayParts[numberOfParts - 1];
return result.UppercaseFirst();
}
从https://codereview.stackexchange.com/questions/24995/convert-timespan-to-readable-text被盗。