除以两个整数不会返回预期结果

我目前正在编写一个需要预览实时显示的程序,但当然,预览会按比例缩小。 但是,当我缩小PictureBox时,大小不正确。 为了使刻度正确,宽度和高度需要为4:3的比例。 这是代码:

 private void FindOptimalRes(PictureBox picBox) { double h = Height / 4; double ratio = 4 / 3; picBox.Size = new Size((int)(h * ratio), (int)h); } 

在测试中, Height (表单的高度)是400,因此,新大小的宽度应该是133.但它总是被调整为100×100! 为什么?

43都是int ,因此它变为1 。 让它们浮点数:

 double ratio = 4.0 / 3.0; 

请注意,你也使用Height犯了同样的错误(现在没关系,但它会 – 将它改为4.0 )。 如果这是实际代码,为什么除以4再乘以4?

 private void FindOptimalRes(PictureBox picBox) { picBox.Size = new Size(Height / 3, Height / 4); } 

你正在进行整数除法:

 double ratio = 4 / 3; // evaluates to 1 

这不会为您提供您正在寻找的值,因为小数点被截断,因此评估为1而不是1.333 。 至少有一个操作数必须是双精度数:

 double ratio = 4.0 / 3.0; // evaluates to 1.333 

同样适用于Height 。 将4更改为4.0

C#的数学是“正确的”。 对正在做的事情的理解是……失踪:-)

表达式4 / 3 (类型为int / int )将计算为数值1,因为它使用整数除法 (两个操作数都是整数)。 然后,结果1在赋值时被隐式强制转换为double值。

另一方面, 4d / 3将“工作”(并导致双重 1.333_),因为现在它是double / int – > double / double (by promotion) – >使用适当的浮点除法 double

类似地,对于Height / 4 (假设Height是一个整数),这些将起作用:

 (double)Height / 4 // double / int -> double Height / 4d // int / double -> double (double)Height / (double)4 // double / double -> double 

快乐的编码!

确保除法结果是double

 double ratio = (double) 4 / 3; // double division 

并且无需将输入值设置为double。

 var num1 = // an integer number var num2 = // an integer number //result is integer, because of integer/integer uses 'integer division' double result = num1 / num2; //result is double , because of you forced to 'double division' double result = (double) num1 / num2; 

也许你应该做一个十进制除法而不是整数除法:

 double h = Height / 4.0; double ratio = 4 / 3.0; 

如果C#Math已关闭,世界各地的许多东西也会被关闭。

你正在进行整数除法。

你需要做的是:

 private void FindOptimalRes(PictureBox picBox) { double h = Height / 4D; // or Height / 4.0 double ratio = 4D / 3D; // or 4.0 / 3.0 picBox.Size = new Size((int)(h * ratio), (int)h); // Size is now correct [133,100] } 

当您使用整数文字(无小数位)进行数学运算时,它会隐式输入为int。

只需在文字末尾添加大写字母D(4D,3D),就可以将它们输入为双精度数,并且数学将是正确的。 或者你可以写4.0,3.0