【问题标题】:Why am I getting the System.OverflowException?为什么我会收到 System.OverflowException?
【发布时间】:2018-11-23 13:30:44
【问题描述】:

这个程序是用 c# 编码的。它应该显示function Log(x,y) 的 3d 图形。我不知道为什么,但每次我运行它时,当它开始绘制图形并且程序停止时,我都会得到System.OverflowException。

我怎样才能防止它发生?为什么会发生?

  private void Draw_Function_Click(object sender, EventArgs e)
    {
        int size = 100;
        double accuracy = 0.09;
        int zoom = 1;
        ver = new double[size, size];
        xtag = new double[size, size];
        ytag = new double[size, size];
        function = Insert_Function.Text;
        for (int i = 0; i < 100; i++)
        {
            for (int p = 0; p < 100; p++)
            {
                ver[i, p] = Math.Log(i,p);
                xtag[i, p] = p * accuracy - i * accuracy * Math.Cos(Math.PI / 5);
                ytag[i, p] = ver[i, p] - i * accuracy * Math.Sin(Math.PI / 5);
            }
        }

        Graphics g = panel1.CreateGraphics();
        for (int i = 0; i < ver.GetLength(0) - 1; i++)
            for (int p = 1; p < ver.GetLength(1) - 1; p++)
            {
                int y0 = (panel1.Height / 2) - (int)(ytag[i, p] * zoom);
                int x0 = (int)(zoom * xtag[i, p]) + panel1.Width / 2;
                int y1 = (panel1.Height / 2) - (int)(ytag[i + 1, p + 1] * zoom);
                int x1 = (int)(zoom * xtag[i + 1, p + 1]) + panel1.Width / 2;  
                g.DrawLine(Pens.Black,
                                 (float)x0,
                                 (float)y0,
                                 (float)x1,
                                 (float)y1);
            }
    }

【问题讨论】:

  • 请将您的代码的文本版本粘贴到问题的正文中。
  • 查看引发异常的行,您的算术运算或强制转换产生的结果对于目标类型来说太大了。
  • @AlexK。我应该怎么做才能使其值适合目标类型?
  • 我首先要看的是对数;未定义零日志(编辑:至少在数学上)...并且以零为底的日志...这是什么意思?即ver[i, p] = Math.Log(i,p); 当i 和p 都是0?
  • @MarcGravell 零日志定义为NegativeInfinity:docs.microsoft.com/en-us/dotnet/api/…

标签: c# integer-overflow


【解决方案1】:

我找到了以下答案:https://social.msdn.microsoft.com/Forums/windows/en-US/9f2b5bba-f725-45c1-9ada-383151267c13/overflow-exception-on-drawline-method-?forum=winforms

引用:“嗨,屏幕坐标允许的最小值是x = -1073741376和y = -1073740288,这是桌面所在的边界,如果再往前走,就会进入void,因此会导致溢出……”

我运行了您的计算,除了它产生 NaN 和 -Infinity 值之外,它还产生了非常小的值,例如 -2147483503。这就是你得到溢出异常的原因。

【讨论】:

    猜你喜欢
    • 2023-04-05
    • 2016-08-21
    • 2014-07-04
    • 2020-06-06
    • 2018-12-26
    • 2021-03-05
    • 2013-07-13
    • 2019-05-28
    相关资源
    最近更新 更多