c# - 整数除以整数返回值以整数形式返回什么

标签 c# math

我想将控件的大小除以窗体的大小,并希望获得它的下限值。 我在想当我尝试将一个整数除以一个整数并将其结果再次存储在 integer 中时会返回什么。

我只想要底价。我尝试使用 Math.FloorMath.Truncate 但它向我显示一个错误,即以下 方法之间的调用不明确 因为编译器无法了解潜水后将返回什么类型的值,即十进制或 double 。

如果我不使用任何此类功能,它会返回底价吗? 我只想要底价。

        Nullable<int> PanelCountInSingleRow = null;
        Nullable<int> widthRemainder = null;

        //setting the size of the panel
        CurrentControlSize = PanelView.Size;
        //Calculate no of Panels that can come in a single row.
        PanelCountInSingleRow = Math.Floor(this.Size.Width / CurrentControlSize.Width);

最佳答案

整数除法向 0 舍入。与发言不完全相同(由于负数向“0”舍入)但我假设你的大小无论如何都是非负的。来自 C# 4 规范,第 7.8.2 节:

The division rounds the result towards zero. Thus the absolute value of the result is the largest possible integer that is less than or equal to the absolute value of the quotient of the two operands. The result is zero or positive when the two operands have the same sign and zero or negative when the two operands have opposite signs.

(请注意,这是专门针对整数除法的。显然浮点除法不会这样做!)

所以基本上您应该能够删除 Math.Floor 调用。

如果你也想得到余数,你可以使用 Math.DivRem :

int remainder;
int count = Math.DivRem(Size.Width, CurrentControlSize.Width, out remainder);

关于c# - 整数除以整数返回值以整数形式返回什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3090635/

相关文章:

C# System.IndexOutOfRangeException 但程序正在运行

math - 计算旋转 45 度后要适合多少正方形

javascript - 如何改进这个 JS Parallax 类型的数学方程?

ios - 如何在标签中输出正确的数字?

C# AntiForgeryToken 属性在 mvc 应用程序中导致 StackOverflowException

c# - 如何隐藏 C# 单元测试?

c# - 计时器、点击、鼠标按下、鼠标弹起事件不能一起工作

c# - 生成 Expression.Assign 以设置小数点时出现异常?从十进制

vb.net - 当我在我的数学运算中放置一个 "="符号时发生了什么?

javascript - 为什么这些列表项的位置不正确?