1

これは私のプログラムのコードです:

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

        }
    }
}

ローカルの Visual Studio 環境を使用して実行しようとすると、自分のプログラムに時間を渡すときの出力minutesが等しいことがコンソールに表示されます。9001.5

これを で実行すると、出力が同じ値でwww.ideone.comあることがわかります。90 minutes1.5

コードのどこで間違いを犯す可能性がありますか? 異なる場所で実行すると、プログラムの動作が異なるのはなぜですか?

4

1 に答える 1

7

ローカルで実行すると、基本的に無視される,桁区切り記号ではなく小数点区切り記号が.使用される文化にいると強く思います。.そのため、最終的には 15 時間、つまり1.5900 分として解析されます。

これを検証するには、1,5代わりに入力してみてください。結果は 90 になると思います。

.が小数点区切り記号である設定を強制したい場合は、カルチャを に渡すだけfloat.TryParseです。

while (!float.TryParse(Console.ReadLine(), NumberStyles.Float,
                       CultureInfo.InvariantCulture, out hours))

すべての計算を自分で行う必要はないことに注意してTimeSpanください。

int minutes = (int) TimeSpan.FromHours(hours).TotalMinutes;
于 2013-09-21T07:22:48.200 に答える