2012-11-11 58 views
3

可能重複:
C#, Operator ‘*’ cannot be applied to operands of type ‘double’ and ‘decimal’倍增文本框的值

嗨,我想乘上在文本框中插入的數值,但我得到錯誤。這是我的代碼。

decimal num1, num2; 
if(decimal.TryParse(textBox1.Text, out num1) 
    && decimal.TryParse(textBox2.Text, out num2)){ 

decimal ans = num1 * 0.20 + num2 * 0.20; 
Label1.Text = ans.ToString(); 

     }else{ 
      MessageBox.Show("Please Put a number!! "); 
     } 

我有錯誤的「ans」請幫助我。這是我的錯誤「運算符*不能應用於'decimal'和double類型的操作數;」

+0

周杰倫,什麼是錯誤信息? – Zbigniew

+0

運算符*不能應用於'decimal'和double類型的操作數; – Jay

+1

然後,這是[http://stackoverflow.com/questions/363706/c-operator-cannot-be-applied-to-operands-of-type-double-and-decimal](http:// stackoverflow.com/questions/363706/c-operator-cannot-be-applied-to-operands-of-type-double-and-decimal) – Zbigniew

回答

3

問題是編譯器將常量視爲Double
要修正錯誤本身,你可以投的常數爲十進制是這樣的:

decimal ans = num1 * (decimal)0.20 + num2 * (decimal)0.20; 

甚至更​​好(如在註釋中規定),你只需specify the type of the constants

decimal ans = num1 * 0.20m + num2 * 0.20m; 
+0

This Works thanks! – Jay

+1

爲什麼在第一個地方使用常量而不是[使它們成爲正確的類型](http://stackoverflow.com/a/166762/11683)?它甚至可能[有害](http://stackoverflow.com/questions/166752/c-sharp-compiler-number-literals/166762#comment6475244_166809)。 – GSerg

+0

GSerg是對的,不需要鑄造。看什麼哈姆雷特Hakobyan寫了 – CSharpie

2
decimal ans = num1 * 0.20m + num2 * 0.20m;