Question

I've got stuck in my program, i need to calculate the gold/minute but my math formula won't do the desire thing. As I input the hours into a float(something like 1.2 hours) the transformation will be 72 min instead of 80 as I need. Can you please help me ? I marked in comment below where the problem is. And here is my code :

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

        }
    }
}

Thanks a lot.

P.S it's related to this question:Allow only numbers to be inserted & transform hours to minutes to calculate gold/min - UPDATED , I update it same as this but i think i should have done a new question as i did now(I'm still learning how to go on with this platform:) )

Was it helpful?

Solution 4

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

And a side note: such way of inputting time is IMO not a good one. It'll be confusing and I guess that more often than not people will be actually entering 1:20 instead of 1.2, which'll break your application. And if not, they might be entering 1.5 thinking of 90 minutes. I know I would have done it like that.

OTHER TIPS

Use the built-in TimeSpan:

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

TimeSpan.FromHours Method Returns a TimeSpan that represents a specified number of hours, where the specification is accurate to the nearest millisecond.

You can also do:

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

Or:

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

If you really want your program to behave as you want do this.

time = (int)hours * 60 + (hours%1)*100
var minutes = TimeSpan.FromHours(1.2).TotalMinutes; // returns 72.0
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top