对于一个家庭作业问题,我们被要求数值找到一个二次方程ax ^2 + bx + c的估计根(其中a,b,c是由用户给定的),我们不能使用-b公式,我们必须使用一个简单的基于搜索的算法来分配。因此,我们必须在x的大范围内找到f(x),然后打印x的值,使f(x)最接近零。
我将f(x)的值存储在一个数组中,并搜索最接近0的值。我想打印x的值,函数的根,这导致了f(x)的值,但不知道如何,我只能打印最接近零的数组中的f(x)的值。
例如,如果a、B和c的值分别为1、-1和-6,我希望输出显示x = 3作为估计根。现在显示的输出是= 0。(f(x)的值,my中最接近零的元素)
这是我的代码:(也很抱歉,如果代码格式不正确,我仍然是新的使用stackoverflow,任何帮助是非常感谢)
/*==================================================================
* Systems header files
*==================================================================*/
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
/*==================================================================
* Constant definitions
*==================================================================*/
#define SIZE 50
/*==================================================================
* Function definitions
*==================================================================*/
float array_roots(const float [], int); /*my function where i will search for my root value*/
int main(void)
{
float table[SIZE]; /* array to store the function values f(x) */
float a, b, c, x;
int i;
printf("*********************************************************\n");
printf("Welcome to the quadratic root estimator.\n");
printf("This estimates the value of one root of\n");
printf("f(x)=ax^2+bx+c.\n");
printf("*********************************************************\n");
printf("Enter the coefficients in the form \"a b c\"\n: ");
scanf("%f %f %f",&a, &b, &c);
/*populating array and calling function */
for(i=0; i<SIZE; i++)
{
x = 0 + i*(0.5); /* the range of values of x im using are between 1 and 50*/
table[i] = a*x*x + b*x + c; /* to store the value of f(x) at the correct point in the array */
}
/* Prints out value from the array which is closest to zero
But i want it to print out the root of the function, x which gave the value of f(x) closest to zero*/
printf("There is a root at: x = %.3f\n", array_roots(table, SIZE));
return(0);
}
/*//////////////////////////////////////////////*/
/*function outside of main to find element in array closest to zero */
/*//////////////////////////////////////////////*/
float array_roots(const float table[], int length)
{
int i; /* index for loop over array*/
float root; /* 'running' root. This will eventually be the root element of the array */
root = table[0]; /* At the beginning, assume that the first element is the root */
/* Next, loop through the array. For each element encountered,
if this element is closer to zero, then
set the running root equal to this value */
for(i=1; i<length; i++)
if(table[i] == 0 || abs(0-table[i]) < abs(0-root))
root = table[i];
/* At this point, variable 'root' holds the correct root element */
return(root);
}
1条答案
按热度按时间chy5wohz1#
有一个表达式将数组索引
i
转换为x值:x = 0 + i*(0.5)
为了使此操作更简单,请添加一个函数来执行此转换
然后你可以把这个函数放到main中:
现在你已经有了这个函数,你可以更新
array_roots
来使用它:正如你所看到的,这将打印出用于查找根的x坐标。