我正在用 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/