用0来定义替换

时间:2014-03-01 08:01:23

标签: c++ c-preprocessor

所以,我正在写一个相对简单的脚本来采用梯形近似的积分。我让它很容易返回结果,但给出了错误的答案。在排除故障的同时,我的许多预处理程序定义开始在所有地方添加零。

    #include <iostream>
    #include <cstdlib>
    #include <sstream>
    #include <cmath>

    #define PI 3.141592
    #define SLICES 25
    #define FORMULA sqrt(1+sinh(x)*sinh(x))
    #define DELTA_X (UPPERBOUND-LOWERBOUND)/SLICES
    #define LOWERBOUND 0
    #define UPPERBOUND 3

    using namespace std;

    int i=0;
    double x;
    double y[SLICES];
    double length=0;

    int main() {


    x=LOWERBOUND;

    cout << DELTA_X << endl;

    while(i<SLICES+1) { //Preparing y values to calculate in next FOR loop




    y[i] = FORMULA;


    i++;
    x+=(DELTA_X);
    cout << "x" << i << " is " << x << endl;
    }

    for(i=0;i<SLICES;i++) {

       double s = (DELTA_X)*(y[i]+y[i+1])/2;


       length+=s; 

        cout << "Length" << i+1 << " is " << s << endl; 
       }



        cout << "The approximate integral sliced " << SLICES << " times is: " << length << endl;


        return 0;
        }

输出基本上在打印时将所有x值,长度值和DELTA_X显示为0。当它突然开始打印0时我改变了公式和其他一些小东西,所以我试图改回来,但没有运气。我最初认为这是因为我试图“嵌套”定义语句(即使它正在工作)所以我尝试用标准整数替换它们。结果相同。任何线索我在做什么。

3 个答案:

答案 0 :(得分:4)

虽然其他答案告诉您如何修复宏,但通常更方便的方法是抛弃宏并用常量值和内联函数替换它们:

static const double   PI         = 3.141592;
static const unsigned SLICES     = 25;
static const double   LOWERBOUND = 0;
static const double   UPPERBOUND = 3;
static const double   DELTA_X    = (UPPERBOUND-LOWERBOUND)/SLICES;

对所有事情仍然如此,对吧?但是,UPPERBOUNDLOWERBOUND现在是双倍的,并且(3-0)/ 25不再导致0,这就是你的0错误的原因。对于FORMULA,请使用内联函数:

inline double FORMULA(double x){
    return sqrt(1+sinh(x)*sinh(x))
}

请注意,在这种情况下,您需要修复FORMULA的出现,例如

y[i] = FORMULA(x);

答案 1 :(得分:1)

#define SLICES 25
#define DELTA_X (UPPERBOUND-LOWERBOUND)/SLICES
#define LOWERBOUND 0
#define UPPERBOUND 3

请注意,DELTA_X被替换为(3-0)/25,由于它是整数除法,因此等于0。

您应该将DELTA_X重新定义为

#define DELTA_X ((double)((UPPERBOUND)-(LOWERBOUND))/(SLICES))

答案 2 :(得分:1)

DELTA_X使用的变量必须是float

#define LOWERBOUND 0.0f
#define UPPERBOUND 3.0f

否则DELTA_X始终为0.