计算任何正值或负值的正确乘法所需的数学是什么?

What is the math needed to compute the correct multiplication for any positive or negative value?

我有一个快速实用的实用程序,可以拍摄图像并调整它们的大小。它允许用户 select "increase" 或 "decrease" 机器人图像的高度和宽度。它似乎工作,除非 "decrease" 被 selected,并且要减少的百分比值是 100 或更多。显然我的代码:

private void buttonApplyPercentageChange_Click(object sender, EventArgs e)
{
    int origHeight = _imgToResize.Height;
    int origWidth = _imgToResize.Width;
    // Two ways to convert the val
    double heightFactor = (double)numericUpDownHeight.Value / 100.0;
    double widthFactor = Convert.ToDouble(numericUpDownWidth.Value) / 100.0;
    if (checkBoxHeightIncrease.Checked)
    {
        heightFactor = 1.0 + heightFactor;
    }
    if (checkBoxWidthIncrease.Checked)
    {
        widthFactor = 1.0 + widthFactor;
    }
    var newHeight = Convert.ToInt32(origHeight*heightFactor);
    var newWidth = Convert.ToInt32(origWidth*widthFactor);
    textBoxNewHeight.Text = newHeight.ToString();
    textBoxNewWidth.Text = newWidth.ToString();
}

...没有考虑这种特定情况。

无论 increase/decrease 以及输入的百分比是否 >= 100,我必须如何正确计算新大小?

将图片尺寸缩小 100% 以上是什么意思?如果将其减小 100%,则大小变为零。减少超过该值将毫无意义,因为您不能拥有负高度和负宽度的图像。我会显示一个对话框,告诉用户他们不能将大小减小超过 100%(如果 heightFactor < 0 || widthFactor < 0)。

What must I do to correctly compuete the new size regardless of increase/decrease and whether the percentage entered is >= 100?

if (!checkBoxHeightIncrease.Checked && heightFactor > 1 ||
    !checkBoxWidthIncrease.Checked && widthFactor > 1)
{
    // show an error
}

您不能将图片的宽度或高度减小超过 100%。将尺寸减小 100% 会使尺寸为零。进一步降低它会使它变为负值。这就是你 运行 惹上麻烦的原因。

我建议您去掉 increase/decrease 复选框,让用户只输入相对于当前大小 的百分比(即 100% 没有变化)。然后你的代码变成:

private void buttonApplyPercentageChange_Click(object sender, EventArgs e)
{
    int origHeight = _imgToResize.Height;
    int origWidth = _imgToResize.Width;

    // Two ways to convert the val
    double heightFactor = (double)numericUpDownHeight.Value / 100.0;
    double widthFactor = Convert.ToDouble(numericUpDownWidth.Value) / 100.0;
    if (heightFactor < 0 || widthFactor < 0)
    {
        // show an error - no negative values allowed
    }
    var newHeight = Convert.ToInt32(origHeight*heightFactor);
    var newWidth = Convert.ToInt32(origWidth*widthFactor);
    textBoxNewHeight.Text = newHeight.ToString();
    textBoxNewWidth.Text = newWidth.ToString();
}
if( heightFactor > 0 )
{
  textBoxNewHeight.Text = newHeight.ToString();
}
else 
{
  textBoxNewHeight.Text =origHeight.ToString(); 
}

if( widthFactor > 0)
{
  textBoxNewWidth.Text = newWidth.ToString();
}
else
{
  textBoxNewWidth.Text =origWidth.ToString(); 
}

要防止用户选择低于最后一个有效值 -100 的数字,只需更改数字编辑框 numericUpDownHeightnumericUpDownWidth 中的最小值 属性表单设计器为 -100。

正如其他人所说,您无法计算比原始数字小 100% 以下的整数(0、1、2...没有负数或分数),您将需要一个要调整到的整数。