2013-09-21 50 views
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環境來運行它,我在控制檯看到,經過1.5小時後當minutes輸出等於900我程序。

如果我運行這個www.ideone.com,我看到輸出爲90 minutes爲相同的值1.5

我在哪裏可以在我的代碼中犯錯誤? 爲什麼我的程序在不同的地方運行時有所不同?

+0

您應該考慮爲您的問題提供良好的標題。 – Praveen

回答

7

我強烈懷疑當您在本地運行它時,您處於,是小數點分隔符而不是.的文化 - 也許.是千位分隔符,它基本上被忽略。因此1.5最終被解析爲15小時,即900分鐘。

爲了驗證這一點,嘗試輸入1,5,而不是 - 我懷疑,那麼你會得到90

因此如果你想強制設置裏.是小數點分隔符,只需通過一個文化融入float.TryParse

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

請注意,您不需要自己完成所有的算術運算 - 請使用TimeSpan爲您完成。

int minutes = (int) TimeSpan.FromHours(hours).TotalMinutes; 
+0

非常感謝您的幫助!有效。 – Victor

相關問題