Home > Software engineering >  If I have one variable as int, and use it for calculating other of type float, why is result shown a
If I have one variable as int, and use it for calculating other of type float, why is result shown a

Time:01-23

I'm doing an equation solver. The code goes like this:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    printf("Equation solver of type ax   by = 0, for y\n");
    int a, b, x;
    float y;
    printf("Enter value of a as integer: ");
    scanf("%d", &a);
    printf("Enter value of b as integer: ");
    scanf("%d", &b);
    printf("Enter value of x as integer: ");
    scanf("%d", &x);
    y = a*x/b; //We have equation ax   by = 0, from that: ax = by, and that is: y = ax/b
    printf("Solution for y of equation: %dx   %dy = 0, for x = %d, is: %.2f", a, b, x, y);
    return 0;
}

When I enter a = 3, b = 5 and x = 3, the output is supposed to be 1.80, but I get 1.00. Why is this? Wouldn't expression a*x/b be converted into type of float? I'm just beginner and we only mentioned type conversion with our professor, maybe I got it wrong?

CodePudding user response:

In a*x/b all variables are ints so it's a pure integer calculation.

If you cast one of the first operands used to float, the other will also be implicitly converted to float

y = (float) a * x / b;

More about what implicit conversions there are can be found here: Implicit conversions

CodePudding user response:

Wouldn't expression a*x/b be converted into type of float?

The result of that expression gets converted to float before being assigned to y. Since each operand has type int, the math is done with that type.

Specifically, a*x and b both have type int, so integer division is performed which truncates the fractional part.

If you cast one of the variables to type float, then floating point division will be performed.

y = (float)a*x/b;
  • Related