C++ 和内联汇编代码在一个程序中具有相同的输出,但在另一个程序中具有不同的输出

标签 c++ visual-c++ x86 inline-assembly x87

我正在做一项作业,必须将一段 C 代码转换为内联汇编。该代码是呈现 Julia 分形的程序的一部分。

我已经测试了两个代码片段的输出,它们完全匹配,但我的程序仍然输出不同的图像(C 代码的正确 Julia 分形,内联汇编代码的平坦粉红色屏幕)。

这是函数的起始部分以及返回

COLORREF render_point(const double &a, 
                      const double &b, int N) {
  double cRe = -0.5;
  double cIm = -0.05;
  double x(a), y(b);
  double norm = x*x+y*y;
  int n;
  double three = 3.0;

  (loop goes here)

  return HSVtoRGB(n % 256, 255 , 255 *(n<N));
}

这是 C 代码

for (n = 0; norm < 4.0 && n < N; ++n) 
{
    double old_x = x;
    double old_y = y;

    x = (old_x * old_x * old_x) - (3 * old_y * old_y * old_x) + cRe;
    y = (3 * old_y * old_x * old_x) - (old_y * old_y * old_y) + cIm;

    norm = x*x+y*y;
}

和内联汇编代码:

for (n = 0; norm < 4.0 && n < N; ++n) 
  {
    __asm {
        // Create (old_x * old_x * old_x)
        fld x;
        fmul x;
        fmul x;

        // Create (3 * old_y * old_y * old_x)
        fld three;
        fmul y;
        fmul y;
        fmul x;

        // Create the full equation for x
        fsubp st(1), st(0);
        fadd cRe;

        // Create (3 * old_y * old_x * old_x) + cIm
        fld three;
        fmul y;
        fmul x;
        fmul x;
        fadd cIm;

        // Create (old_y * old_y * old_y)
        fld y;
        fmul y;
        fmul y;

        fsubp st(1), st(0); // Create the full equation for y

        fst y;              // Store in y to use for next loop
        fmul st(0), st(0);  // Get y*y

        fxch st(1);         // Swap places of y*y with newly calculated x
        fst x;              // Store in x to use for next loop

        fmul st(0), st(0);  // Get x*x

        faddp st(1), st(0); // Get x*x + y*y
        fst norm;           // Set loop variable
    }
  }

两个循环之间是否存在可能导致程序输出不同的差异?

最佳答案

正如 1201ProgramAlarm 在评论中提到的那样,只需在每次循环迭代结束时从 FPU 中弹出剩余值范数即可。

关于C++ 和内联汇编代码在一个程序中具有相同的输出,但在另一个程序中具有不同的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46386567/

相关文章:

c++ - 谁能解释一下((a == 1 && a == 2 && a == 3)== true)?

c++ - "virtual void IBase::Foo"和 "virtual void Foo"之间有什么区别吗?

operating-system - 识别通用保护故障 (x86) 上的故障地址

来自控制台的 C++ 输入,比较整数

assembly - X86指令在实模式下关闭计算机?

assembly - 减去两个字符

c++ - 从用户定义的函数转到 main()

c++ - 根据下面的作者,如果两个指针指向不同的数组,比较的第一个版本将是未定义的

c++ - cout 中出现意外输出

c++ - 是否存在 C4129 警告未指示错误的真实案例?