【发布时间】:2015-12-15 03:06:53
【问题描述】:
我正在尝试编写 C 代码来执行一些数学计算。我正在使用 printf 语句来检查 print 变量。当我完成代码并获得所需的输出时,我将这一行注释掉了。但是,在这样做之后,我没有得到任何输出。取消注释该行将返回所需的输出。
#include <stdio.h>
#include <math.h>
#define M 1000
const double eps = 1.110223e-16;
const double delta = 1.110223e-16;
void bisection(double (*fn)(double), double a, double b) {
//Bisection algorithm
double w, c, u, v, e;
int i;
u = (*fn)(a);
v = (*fn)(b);
e = b - a;
if(signbit(u) == signbit(v)) {
printf("Stopping due to same sign\n");
return;
}
for(i = 0; i < M; i++) {
printf("%d\n", i);
e = e / 2;
c = a + e;
w = (*fn)(c);
//Stopping conditions epsilon and delta
if(abs(e) <= eps || abs(w) <= delta) {
printf("Root is %e\n", c);
return;
}
if(signbit(w) == signbit(u)) {
//Means that root lies in [c,b]
a = c;
u = w;
} else {
// Means root lies in [a, b]
b = c;
v = w;
}
}
}
double problem_a(double x) {
return (pow(x, -1) - tan(x));
}
int main(int argc, char *argv[])
{
double (*fn)(double);
fn = &problem_a;
bisection(fn, 0.0 + eps, M_PI/2 - eps);
return 0;
}
我得到的输出是:Root is 7.853982e-01 如果我评论文件,我不会得到任何输出。
我使用的是 gcc 编译器版本 4.8.3
对这种行为有什么可能的解释?
【问题讨论】:
-
您的代表建议您已经存在了足够长的时间,因此知道最好不要将代码仅留在粘贴站点中。将其设为 MCVE (How to create a Minimal, Complete, and Verifiable Example?) 并将代码包含在问题中。
-
abs()为double?使用fabs()(更重要的是启用警告)。 -
对于
if(abs(e) <= eps || abs(w) <= delta) {行,尝试添加代码以输出所有这些变量,并比较两次运行之间的变化 -
@Ari0nhh 当“在 MSVC 中正常工作”时,C 编译是 C++ 编译的吗?
-
@chux 两者都有,尽管 C++ 得到的结果与 C 略有不同。C 编译器还会在
abs函数上生成 double to int 截断警告,这很可能是问题根源。