Search code examples
cinteger

dividing or multiplying integers result in 0.0000 every time


when i try print preTopping the answer is always 0.0000 even after adding (float) beforehand

int length, width;
printf("Please enter your pizza's length (cm): ");
scanf(" %d", &length);
printf("Please enter your pizzas width (cm): ");
scanf(" %d", &width);

float preTopping, postTopping=0;
preTopping = ((length * width) / (40 * 40)) * 60;
printf("%f", preTopping);

Solution

  • In this expression:

    ((length * width) / (40 * 40)) * 60;
    

    All operands have type int. This means that integer division is done, and integer division truncates any fractional part. So if length * width is less than 1600, the result of the division will be 0 since that's the integer part of the result.

    If you want to use floating point division, you need to cast at least one operand of the division to a floating point type:

    preTopping = ((float)(length * width) / (40 * 40)) * 60;