c - split 的意外结果

标签 c division

我尝试实现以下计算:

#include <stdio.h>
#include <math.h>

int main(){

    float sum = 0;
    int c = -4;
    float x1 = 136.67;
    float x2 = 2.38;

    sum = c / (pow(abs(x1 - x2), 2));
    printf("%f %f %f",sum,x1,x2);

    return 0;
}

但是sum执行后的值竟然是-4。怎么了?

最佳答案

abs<stdlib.h> 中声明.它需要一个 int参数并返回 int结果。

失踪的#include <stdlib.h>也很可能会导致问题。您正在调用 abs使用浮点参数;如果没有可见的声明,编译器可能会假设它需要一个 double参数,导致代码不正确。 (这是根据 C90 规则;根据 C99 规则,该调用违反了约束,需要进行编译时诊断。)

你想要 fabs <math.h> 中定义的函数.

关于c - split 的意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23525379/

相关文章:

c - 链表removeNode C编程

java - 从 Java 代码调用 C 可执行文件后没有得到任何输出

perl - 如何计算 float 的 div 和 mod?

Python:rtruediv 没有像我预期的那样工作

c++ - 编译器是否优化了常数整数除法?

python - 将值转换为 %

C 中的凯撒密码 : can't seem to wrap around the latter letters of the alphabet

c - 如何捕获对设备文件的写入和读取

c - c中for循环的测试计数器中的s[i]

c - 编写一个程序,提示用户输入球体的半径并打印其体积