简体   繁体   English

C中的霍纳法则

[英]Horner's rule in C

So I am writing a program that calculates the polynominals using the Horner's rule. 因此,我正在编写一个使用Horner规则计算多项式的程序。

But after I enter the first coefficient the program crashes. 但是在我输入第一个系数后,程序崩溃了。 What did I do wrong? 我做错了什么? I can't find the error. 我找不到错误。

EDIT: I just noticed that I was reading in the arguments backwards. 编辑:我只是注意到我在向后读参数。

int main() {

    int degree;
    float x;
    float px = 0;
    float p = 0;
    float *a;
    int i;

    a = malloc((degree+1)*sizeof(float));

    printf("Enter the degree:");
    scanf("%d", &degree);
    printf("Enter the argument:");
    scanf("%f", &x);

    for (i = 0; i < degree+1; i++)
    {
    printf("Enter the coefficient Nr%d:", i+1);
    scanf("%f", *(a+i));
    }   
    for (i = degree; i > -1; i--)
    {
    p = *(a+i) * pow(x, i);
    px + p;
    }

    printf("%f", px);

    return 0;
}

When you allocate memory for a , degree is yet to be initialized. 当您分配内存adegree尚未被初始化。

Also, remove the asterisk from scanf("%f", *(a+i)); 同样,从scanf("%f", *(a+i));删除星号scanf("%f", *(a+i)); . You want the address of a[i] , not its value . 您需要a[i]地址 ,而不是其value

In your code, a = malloc((degree+1)*sizeof(float)); 在您的代码中, a = malloc((degree+1)*sizeof(float)); you are using the value of degree without initializing it. 您正在使用degree的值而不进行初始化。 An initialized variable can contain ANY value, most likely to be invalid and will take you to the scenario called undefined behavior . 初始化变量可以包含ANY值,最有可能是无效的,并将带您进入未定义行为的场景。 That's why the crash is there. 这就是崩溃发生的原因。

Second thing, every time after a malloc() [or in general, a library function or a system call] , its a very good idea to check for the validity of the return vale. 第二件事,每次执行malloc() [或者通常是库函数或系统调用]之后,检查返回值的有效性都是一个好主意。 Here you can make use of NULL check on the a variable after the malloc() . 在这里,您可以对malloc()之后的a变量使用NULL检查。

Third, change the scanf("%f", *(a+i)); 第三,更改scanf("%f", *(a+i)); to scanf("%f", &a[i]); scanf("%f", &a[i]); .

Maybe if you write the code in following way, it should work. 也许如果您以以下方式编写代码,它应该可以工作。

int main() {

    int degree;
    float x;
    float px = 0;
    float p = 0;
    float *a;
    int i;

    printf("Enter the degree:");
    scanf("%d", &degree);
    printf("Enter the argument:");
    scanf("%f", &x);

    a = malloc((degree+1)*sizeof(float));

    for (i = 0; i < degree+1; i++)
    {
    printf("Enter the coefficient Nr%d:", i+1);
    scanf("%f", &a[i]);
    }   
    for (i = degree; i > -1; i--)
    {
    p = *(a+i) * pow(x, i);
    px + p;
    }

    printf("%f", px);

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM