C程序求根错误

标签 c function imperative-programming

我正在用 C 编写一个具有以下规范的函数:

float find_root(float a, float b, float c, float p, float q);

find_root 取二次方程的系数 a、b、c 和区间 (p, q)。它将返回给定区间内该方程的根。

例如:find_root(1, -8, 15, 2, 4) 应该产生“接近”3.0 的根

我写了下面的代码,但我不明白为什么它不起作用:

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

main()
{
    printf("Hello World");
}

float find_root(float a, float b, float c, float p, float q) {

    float d,root1,root2;  
    d = b * b - 4 * a * c;
    root1 = ( -b + sqrt(d)) / (2* a);
    root2 = ( -b - sqrt(d)) / (2* a);

    if (root1<=q || root1>=p)
    {
        return root1;
    }
    return root2;
}

请告诉我错误是什么。

最佳答案

您的程序无法运行,因为您从未从 main() 中调用过 find_root()

find_root() 不应该 all-by-itself 运行。您的程序从 main() 开始执行。您需要从 main() 调用您的子函数才能执行它们。

将您的 main 更改为调用 find_root(),如下所示。

int main()                              //put proper signature
{

float anser = 0;

answer = find_root(1, -8, 15, 2, 4);   //taken from the question
printf("The anser is %f\n", answer);        //end with a \n, stdout is line buffered

return 0;                                 //return some value, good practice

}

然后,像这样编译程序

gcc -o output yourfilename.c -lm

除此之外,对于find_root()函数中的逻辑问题,请按照@paxdiablo先生的建议进行。

关于C程序求根错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28360006/

相关文章:

excel - 每 6 行将单元格引用增加 1

haskell - 将带有break-s/continue-s的命令式控制流转换为haskell

c++ - 更好的可读性和简单性与更高的复杂性和编程速度,该选择什么?

c++ - exe 可以小于其最大的声明缓冲区吗?

javascript - 箭头函数中的三元运算符

c - 我需要在 getline() 失败后调用 free() 吗?

c++ - 如果您不知道传递的方法的确切类,如何将方法传递给类

javascript - Underscore.js - 命令式和功能性练习

c - 为什么我们必须在同一台机器上为不同的操作系统重新编译 c 源代码?

c - 我的文字在哪里?