我编写了一个程序,用于在用户决定作为输入的范围内查找五次多项式的根。 例如:
请输入多项式的系数: -64 0 0 0 0 2
请输入范围:
4 -5.7
范围无效!请输入范围:
2 3.5
多项式有根:x=2。
我的问题是,当我输入范围 **10.4 10.2"时,程序无法比较两个值并确定其范围无效。对于整数,它可以工作。
我该如何解决这个问题?
#include <stdio.h>
#define ZERO 0.00001
int main()
{
double a_0,a_1,a_2,a_3,a_4,a_5,end_of_range,beginning_of_range;
int x,root;
printf("Please enter the coefficients of the polynomial:\n");
scanf("%lf%lf%lf%lf%lf%lf", &a_0, &a_1, &a_2, &a_3, &a_4, &a_5);
printf("Please enter the range:\n");
scanf("%lf%lf", &beginning_of_range, &end_of_range);
while (beginning_of_range >= end_of_range)
{
printf("Invalid range! Please enter the range:\n");
scanf("%lf%lf", &beginning_of_range, &end_of_range);
}
x = beginning_of_range;
while (x <= end_of_range)
{
if ((a_0 + a_1*x + a_2*x*x + a_3*x*x*x + a_4*x*x*x*x + a_5*x*x*x*x*x >= -ZERO)
&& (a_0 + a_1*x + a_2*x*x + a_3*x*x*x + a_4*x*x*x*x + a_5*x*x*x*x*x <= ZERO))
{
root = x;
printf("The polynomial has the root x=%d.", root);
break;
}
x++;
if( x > end_of_range)
{
printf("Could not find a root.");
break;
}
}
return 0;
}
注意:我希望根只能是整数!这就是为什么我将 x
声明为 int
。
发生了一些奇怪的事情,当我输入范围 [10.4, 10.3] 时,它只等待大约 1 分钟,然后打印“无法找到根”,尽管它必须打印无效范围。
最佳答案
要改变的事情:
更改
x
的类型。而不是int x;
使用
double x;
将
root
声明为变量。double root;
修复用于打印
root
的格式。而不是printf("The polynomial has the root x=%d.", root);
使用
printf("The polynomial has the root x=%lf.\n", root);
关于c - 读取 "Scanf"语句中的 double 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29545279/