Home  >  Q&A  >  body text

c++ - 同样的源代码在visual studio能正确执行,g++运行结果有问题?

追赶法解线性方程组。

代码如下:

#include <iostream>
#include <cmath>

using namespace std;

void MyAlgorithm(double a[], double b[], double c[], double d[], int size)
{
    if (abs(b[0]) > abs(c[0]) && abs(c[0]) > 0 && 
        abs(b[size - 1]) >= abs(a[size - 1]) && abs(a[size - 1]) > 0)
    {
        int i;
        for (i = 1; i != size - 1; ++i)
        {
            if (abs(b[i]) < abs(a[i]) +abs(c[i]) || 
                a[i] * c[i] == 0)
            {
                cout << "不满足追赶法条件!" << endl;
                return;
            }
        }
        for (i = 1; i != size; ++i)
        {
            a[i] = a[i] / b[i - 1];
            b[i] = b[i] - a[i] * c[i - 1];
            d[i] = d[i] - a[i] * d[i - 1];
        }
        d[size] = d[size] / b[size];
        for (i = size - 1; i != -1; --i)
        {
            d[i] = (d[i] - c[i] * d[i + 1]) / b[i];
        }
    }
    else cout << "不满足追赶法条件!" << endl;
    return;
}

int main(int argc, char const *argv[])
{
    double a_0[4] = { 0, -1, -1, -1 };
    double b_0[4] = { 2, 2, 2, 2 };
    double c_0[4] = { -1, -1, -1, 0 };
    double d_0[4] = { 5, -12, 11, -1 };
    int i;
    MyAlgorithm(a_0, b_0, c_0, d_0, sizeof(a_0) / sizeof(double));
    for (i = 0; i != sizeof(a_0) / sizeof(double); ++i)
    {
        cout << "x_" << i + 1 << '\t' <<d_0[i] << endl;
    }
    cout << endl;
    return 0;
}

使用vs 2015能输出正确结果,而g++编译则为nan。。。

发现第27行会改变c[0]值。。。不懂。。。

求问。

大家讲道理大家讲道理2764 days ago569

reply all(1)I'll reply

  • 迷茫

    迷茫2017-04-17 13:39:10

    void MyAlgorithm(double a[], double b[], double c[], double d[], int size)
    {
        if (abs(b[0]) > abs(c[0]) && abs(c[0]) > 0 && 
            abs(b[size - 1]) >= abs(a[size - 1]) && abs(a[size - 1]) > 0)
        {
            int i;
            for (i = 1; i != size - 1; ++i)
            {
                if (abs(b[i]) < abs(a[i]) +abs(c[i]) || 
                    a[i] * c[i] == 0)
                {
                    cout << "不满足追赶法条件!" << endl;
                    return;
                }
            }
            for (i = 1; i != size; ++i)
            {
                a[i] = a[i] / b[i - 1];
                b[i] = b[i] - a[i] * c[i - 1];
                d[i] = d[i] - a[i] * d[i - 1];
            }
            d[size] = d[size] / b[size];                  // 这一行数组 d 和 b 访问越界了
            for (i = size - 1; i != -1; --i)
            {
                d[i] = (d[i] - c[i] * d[i + 1]) / b[i];
            }
        }
        else cout << "不满足追赶法条件!" << endl;
        return;
    }

    reply
    0
  • Cancelreply