2012-03-07 46 views
2

我正在使用Google天氣XML文件在C#中開發天氣應用程序,並且在類文件中使用計算時遇到問題。我想華氏轉換爲攝氏與folliowing方法:從雙倍轉換爲小數

public static class Helper 
{ 
    public static decimal CalculateTemp(decimal input) 
    { 
    return Math.Round((input - 32) * 5/9/1.0) * 1.0 + "°C"; 
    } 
} 

「輸入」是那裏的天氣數據被稱爲如最高溫度。今天的。

錯誤23:我在編譯收到以下錯誤的最佳重載的方法匹配「Weather.Helper.CalculateTemp(十進制)」有一些無效參數

錯誤24:參數1:不能轉換從「雙」到「小數」

錯誤25:不能應用於類型「十進制」和「雙師型」

的操作數我不知道如何解決這個操作「/」 ..

+3

編寫健全的代碼,不要除以1,不要乘以1,不要將字符串附加到浮點數,編譯器將會「啊,所以這就是您的實際意思」。 – 2012-03-07 12:38:19

回答

6

不要使用decimal作爲溫度,double就足夠了。

另外,不要返回"°C"因爲它是一個數字,而不是字符串:

public static double CalculateTemp(double input) 
{ 
    return Math.Round((input - 32) * 5/9); 
} 
+1

這麼說。而且由於他四捨五入到了整數,他根本不需要浮點數。但他的問題是錯誤來自哪裏,錯誤信息表明這個例子是他的實際程序的一個非常簡化的例子,所以也許他確實需要一個'decimal'。 – 2012-03-07 12:37:59

+0

非常感謝! – 2012-03-07 13:14:17

5

1.0double,而不是一個decimal。使用後綴mM將數字標記爲decimal
(「M」代表「金錢」,因爲這類型通常用於金融交易。)

(input - 32) * 5M/9M 

,你甚至不會需要* 1.0

0

,如果你想使用十進制(而不是雙),你就必須爲重構:

public static class Helper 
{ 
    public static string CalculateTemp(decimal input) 
    { 
     return Math.Round(((input - 32) * 5/9/1.0m)) + "°C"; 
    } 
} 

或:

public static class Helper 
{ 
    public static string CalculateTemp(decimal input) 
    { 
     return Math.Round(((input - 32) * 5/9/(decimal)1.0)) + "°C"; 
    } 
} 

還注意到,由於末尾有"°C",您必須更改方法簽名才能返回字符串。