定义替换为 0
define replacing with 0s
所以,我正在编写一个相对简单的脚本来取积分的梯形近似。我很容易让它返回结果,但给出了错误的答案。在排除故障时,我的许多预处理器定义开始到处放置零。
#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;
这仍然对所有事情都做同样的事情,对吧?但是,UPPERBOUND
和 LOWERBOUND
现在是双打,并且 (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。
相关文章:
- 如何在 c++ 中定义一个将被另一个短语替换的短语?
- 用矩阵将函数中的整数值替换定义的常量
- 将前向声明的结构替换为最近定义的结构
- 替换预处理器定义中的字符
- 替换包含已弃用的一元函数的自定义模板
- 尝试在自定义 QT 创建器文本编辑器中创建查找和替换循环.我似乎无法设置光标位置
- Visual Studio 快速替换宏及其定义
- 替换 C 代码宏并在C++代码中定义常量
- 用自定义说明替换每个乘法
- 如何用自定义小部件替换QListWidget的图标?
- 将"定义宏"替换为空实现
- 定义替换为 0
- 将类定义宏替换为模板
- 用定义替换std :: cout
- 将所有函数调用替换为 C/C++ 代码中的定义
- gtkhow用自定义标题替换所有标题
- 我是否可以使用用户定义的转换将原始指针访问替换为通过类访问
- #定义具有多个替换项的指令
- 将文本文件中的特定单词:C++替换为预定义值
- 替换SHDOCLC.DLL文件以自定义网络浏览器的上下文菜单