将分钟转换为小时

时间:2013-09-19 08:29:34

标签: c# minute

我被困在我的程序中,我需要计算金/分钟,但我的数学公式不会做欲望的事情。当我将小时数输入浮点数(类似于1.2小时)时,转换将是72分钟而不是80分钟。 你能帮我么 ?我在下面的评论中标出了问题所在。 这是我的代码:

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();

        }
    }
}

非常感谢。

PS它与这个问题有关:Allow only numbers to be inserted & transform hours to minutes to calculate gold/min - UPDATED,我更新它与此相同,但我想我应该像现在一样做一个新问题(我还在学习如何继续使用这个平台: ))

4 个答案:

答案 0 :(得分:3)

使用内置TimeSpan

TimeSpan time = TimeSpan.FromHours(1.2);
double minutes = time.TotalMinutes;
  

TimeSpan.FromHours方法返回表示指定小时数的TimeSpan,其中规范精确到最接近的毫秒。

你也可以这样做:

// 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
}

或者:

var time = new TimeSpan(0, 1, 20, 0);
double minutes = time.TotalMinutes;

答案 1 :(得分:2)

如果你真的希望你的程序按照你想要的方式行事。

time = (int)hours * 60 + (hours%1)*100

答案 2 :(得分:1)

var minutes = TimeSpan.FromHours(1.2).TotalMinutes; // returns 72.0

答案 3 :(得分:0)

var hours = 1.2;
var minutes = ((int)hours) * 60 + (hours%1)*100;

并且附注:这种输入时间的方式是IMO不是一个好的方式。它会让人感到困惑,我想人们实际上会更频繁地输入1:20而不是1.2,这会打破你的申请。如果没有,他们可能会考虑1.5分钟90。我知道我会这样做的。