定义替换为 0

define replacing with 0s

本文关键字:替换 定义      更新时间:2023-10-16

所以,我正在编写一个相对简单的脚本来取积分的梯形近似。我很容易让它返回结果,但给出了错误的答案。在排除故障时,我的许多预处理器定义开始到处放置零。

    #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 时,我更改了公式和其他一些小东西,所以我试图将其更改回来,但没有运气。我最初认为这是因为我试图"嵌套"定义语句(即使它正在工作),所以我尝试用标准整数替换它们。相同的结果。任何线索我在做什么。

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

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);
#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))

DELTA_X使用的变量必须是浮点数

#define LOWERBOUND 0.0f
#define UPPERBOUND 3.0f

否则DELTA_X始终为 0。