简体   繁体   中英

Horner's rule in C

So I am writing a program that calculates the polynominals using the Horner's rule.

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.

Also, remove the asterisk from scanf("%f", *(a+i)); . You want the address of a[i] , not its value .

In your code, a = malloc((degree+1)*sizeof(float)); you are using the value of degree without initializing it. An initialized variable can contain ANY value, most likely to be invalid and will take you to the scenario called undefined behavior . 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. Here you can make use of NULL check on the a variable after the malloc() .

Third, change the scanf("%f", *(a+i)); to 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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