Krishna Kanth Yenumula
Krishna Kanth Yenumula

Reputation: 2567

Polynomial multiplication (ax+b)*(cx+d). Strange output when any co-efficient is floating number

Please see the code below.

#include <stdio.h>
int main()
{
int a, b, c, d;
int p2, p1, p0;

printf("Enter a:");
scanf("%d",&a);
printf("Enter b:");
scanf("%d",&b);
printf("Enter c:");
scanf("%d",&c);
printf("Enter d:");
scanf("%d",&d);

p2 = a*c;
p1 = a*d + b*c;
p0 = b*d;
printf("The product is: %dx^2+%dx+%d\n",p2,p1,p0);
return 0;
}

Output is as follows:

Enter a:1.5

Enter b:Enter c:Enter d:The product is 3x^2+0x+0

Can anyone explain this? Once we give 1.5, it is not accepting the values for remaining co-efficients. How did we get that output?

Upvotes: 1

Views: 95

Answers (2)

Prostagma
Prostagma

Reputation: 1851

Declaration

Declare all parameters as double instead of int. (a, b, c, d, p0, p1, p2)

Double format

When using %d, an int is expected.

Use %lf when working with doubles.

This refers both to scanf and printf.

Code:

#include <stdio.h>
int main()
{
    double a, b, c, d;
    double p2, p1, p0;

    printf("Enter a:");
    scanf("%lf",&a);
    printf("Enter b:");
    scanf("%lf",&b);
    printf("Enter c:");
    scanf("%lf",&c);
    printf("Enter d:");
    scanf("%lf",&d);

    p2 = a*c;
    p1 = a*d + b*c;
    p0 = b*d;
    printf("The product is: %lfx^2+%lfx+%lf\n",p2,p1,p0);
    return 0;
}

Upvotes: 3

First and foremost: the 1.5 in the standard input is not a a floating point value. It's a string of characters which may be interpreted as floating point value. It's also a string of characters that may not be interpreted entirely as an integer.

When scanning it, the 1 may be consumed to scan a value for a. But then the . is encountered, which may not be part of of a character sequence that stands for the value of an integer. So scanf will not consume it, it will stay in the input buffer until some other operation will deal with it.

But you call scanf again, and tell it to expect an integer. It still sees the ., which it can't handle. So it returns without consuming anything or writing anything into the argument you've given it. It reports the result of the operation in its return value, that you neglect to check. On the whole, your code doesn't take any error handling into account. It's written with the assumption scanf will always succeed, which is not realistic. You can read about scanf's return value here.

Beyond that, you don't initialize any of your variables. That leaves them with indeterminate values. If scanf succeeds, those variables get assigned something else and your program runs successfully. But if scanf fails they don't, and you use those indeterminate values, resulting in your program having undefined behavior. There's no point trying to understand undefined behavior. You should fix your code instead. And you do that by handling failure properly. How you choose to handle scanf's failure is up to you.

Upvotes: 2

Related Questions