非常基本的除法方程在c#中不起作用

我不能把它分成小数。 它的四舍五入值为0。

private void button24_Click(object sender, EventArgs e) { double x = 0; x = 1 / 2; ans.Text = x.ToString(); } 

当我调试时,x在发送到文本框’ans’之前为零。

我试过……字符串变量仍为零..

 double x = 1/5; string displayX = x.ToString("0.0000"); 

它是整数除法 ,它们是预期的输出。

 double x = 1.0 / 5; // this will not perform integer division double x = 1/5; // this does (1/5 = 0). double x = 1D / 5; // this will not because 1 is treated as a double 

您可以执行以下操作之一:

 double x = 1; double y = 1.5; double ans = x / y; 

用双x = 1.0 / 5替换双x = 1/5,这应该修复它。 因为你要划分的数字都是整数,所以它仍然将它作为整数处理,而不是作为一个整数。 当你在逻辑上思考时,它有一定意义 – 它以这些数字的任何forms进行除法,然后将其保存到变量中; 变量类型对于实际等式是无关紧要的。

(我意识到还有其他答案,但希望这可以帮助您了解问题存在的原因。)