程序行为在不同系统上是不同的.为什么?

Vic*_*tor 1 c#

这是我的程序代码:

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;
            while (!int.TryParse(Console.ReadLine(), out gold))
            {
                Console.WriteLine("Please enter a valid number for gold.");
                Console.WriteLine("Inesrt your gold: ");
            }
            Console.WriteLine("Inesrt your time(In Hours) played: ");
            float hours;
            while (!float.TryParse(Console.ReadLine(), out hours))                
                    {
                        Console.WriteLine("Please enter a valid number for hours.");
                        Console.WriteLine("Inesrt your hours played: ");
                    }
                    float time = ((int)hours) * 60 + (hours % 1) * 100; ; // 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.\n but no thanks");
                    Console.ReadLine();

                    //Console.WriteLine(" \nApp self destruct!");
                    //Console.ReadLine();

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试使用我的本地Visual Studio环境运行它时,我在控制台中看到输出minutes等于9001.5小时数传入程序时的输出.

如果我运行它www.ideone.com,我看到输出是90 minutes相同的值1.5.

我的代码在哪里可以搞错?为什么我的程序在不同的地方运行时的行为有所不同?

Jon*_*eet 7

我强烈怀疑,当你在本地运行它时,你所处的文化,是小数分隔符而不是.- 也许.是千位分隔符,它基本上被忽略了.所以1.5最终解析为15小时,即900分钟.

要验证这一点,请尝试输入1,5- 我怀疑您将获得90的结果.

如果要强制设置.小数点分隔符,只需将文化传递到float.TryParse:

while (!float.TryParse(Console.ReadLine(), NumberStyles.Float,
                       CultureInfo.InvariantCulture, out hours))
Run Code Online (Sandbox Code Playgroud)

请注意,您不需要自己完成所有算术 - 用于TimeSpan为您完成.

int minutes = (int) TimeSpan.FromHours(hours).TotalMinutes;
Run Code Online (Sandbox Code Playgroud)