c - 为什么 fabs 在除 main 之外的其他文件中使用时总是返回整数 1

标签 c linux

在我的 C 代码中,由多个源文件和 header 组成,我必须在我的函数之一中使用 fabs。但每次我使用 fabs 时,它都只返回一个等于 1 的整数。

我在这里找到了一篇讨论这个问题的帖子(其他网站上没有帖子),但答案与我不符。答案是将数学库与 -lm 链接起来,但我已经这样做了,并且包含数学,但我也这样做了......

所以我不明白为什么它返回 1,这对我的实习来说确实很困难,因为它对于整个代码来说是一个重要的函数。

这是我的函数以及 header polynome.hmaths_jauge.h 中的包含内容

#include "maths_jauge.h"

double newtonMethode(double *poly, double valeur, int degre, double x) {
    double scalaire[1];
    scalaire[0] = -valeur;

    double *polyInter = malloc((degre + 1) * sizeof(double));
    additionPoly(degre, poly, 0, scalaire, polyInter);
    free(polyInter);

    int degreDerive = degre - 1;
    double *derive = malloc((degreDerive) * sizeof(double));
    derivePoly(degre, poly, derive);

    while (fabs(evalPoly(x, degre, poly) - valeur) > 0.001) {
        x -= evalPoly(x, degre, polyInter) / evalPoly(x, degreDerive, derive);
    }

    free(derive);
    return x;
}

包含在maths_jauge.h中:

 #include <stdlib.h>
 #include <string.h>
 #include "polynome.h"

包含在polynome.h中:

 #include <math.h>

这是我的 makefile:

CC = gcc
CFLAGS = -Wall -g
LDFLAGS = -lm

all : main.o polynome.o maths_jauge.o
    $(CC) $^ -o main $(LDFLAGS)

main.o : main.c polynome.h
    $(CC) -c $< -o $@ $(CFLAGS)

polynome.o : polynome.c
    $(CC) -c $< -o $@ $(CFLAGS)

maths_jauge.o : maths_jauge.c
    $(CC) -c $< -o $@ $(CFLAGS)

.PHONY : clean mrproper

clean :
    rm -f *.o

mrproper : clean
    rm -f main

最佳答案

以与修复它相同的方式重写代码,所以我仍然不明白为什么它会这样。

谢谢。

这是人们强调的重写后的代码,没有错误:

double newtonMethode(double *poly, double valeur, int degre, double x) {
    double scalaire[1];
    scalaire[0] = -valeur;

    int i = 0;

    double *polyInter = malloc((degre + 1) * sizeof(double));
    additionPoly(degre, poly, 0, scalaire, polyInter);

    int degreDerive = degre - 1;
    double *derive = malloc((degreDerive + 1) * sizeof(double));
    derivePoly(degre, poly, derive);

    while (fabs(evalPoly(x, degre, poly) - valeur) > 0.000001) {
        x -= evalPoly(x, degre, polyInter) / evalPoly(x, degreDerive, derive);
    }

    free(polyInter);
    free(derive);
    return x;
}

关于c - 为什么 fabs 在除 main 之外的其他文件中使用时总是返回整数 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45382625/

相关文章:

c - 需要帮助在 Windows 上严重重定向计时器程序的输入和输出

linux - 比较两行

linux - 使用make构建后的.d文件是什么

linux - 如何找出2个文件之间的差异

c - 3d线程索引和并行化2题

c - Valgrind 条件跳转或移动取决于未初始化的值

linux - 你怎么能有一个回到同一个端口的 TCP 连接?

linux - 在 Linux 工作队列中休眠

c++ - 是什么导致了这种格式字符串攻击?

我可以仅使用 cast 从 long double 转换为 float/double/int 吗?