错误c2106:'=':左操作数必须是I值

时间:2015-03-03 22:34:12

标签: c++ if-statement

我正在尝试在for循环中执行if语句,它给了我以下问题:"错误c2106:' =' :左操作数必须是I值"在我的每个if循环旁边。

#include <iostream>
#include <cmath>
#include <vector>

using namespace std;

// Function of given equation
double function(double x)
{
    double result;
        result = 0.2+25*x-200*pow(x,2)+675*pow(x,3)-900*pow(x,4)+400*pow(x,5);
    return result;
}

int main()

{
    double boundup;         // Upper bound
    double bounddown;       // Lower bound
    double n;               // Number of intervals
    double step;            // Step size
    double fsimp;           // Simpson's rule
    double ftrap;           // Trapezoidal rule 

    cout << "Enter lower bound: " ;
    cin >> bounddown;

    cout << "Enter upper bound: " ;
    cin >> boundup;

    cout << "Number of intervals: " ;
    cin >> n;

    // Vector class for both x and fx
    vector<double> x(n+1);
    vector<double> fx(n+1);

    // Define first and last values in x and fx because they will not change
    step = (boundup-bounddown)/n;
    x[0] = bounddown;
    x[n] = boundup;

    fx[0] = function(x[0]);
    fx[n] = function(x[n]);

    fsimp = fx[0];

    for (int i=0; i<n; i++)
    {
        x[i+1] = x[i]+step;
        fx[i+1] = function(x[i+1]);

        if (i%2=0)
        {
            fsimp = 2*fx[i+1] + fsimp;
        }

        if (i%2=1)
        {
            fsimp = 4*fx[i+1] + fsimp;
        }

        fsimp = fx[n] + fsimp;
    }

    cout << "Bounds of integration: " << bounddown << ", " << boundup << endl;
    cout << "Number of intervals: " << n << '\n' << endl;
    cout << "Integral value of f(x): " << fsimp << endl;

return 0;
}

我只是想用Simpson的规则进行数值积分。我不确定如果发表声明我会怎么做。

1 个答案:

答案 0 :(得分:6)

您需要使用比较(==),而不是分配(=):

    if (i%2=0)
    {
        fsimp = 2*fx[i+1] + fsimp;
    }

应该是:

    if (i%2 == 0)
    {
        fsimp = 2*fx[i+1] + fsimp;
    }