Division result gives zero in decimal places

Question:

On division of 1 by 3, my program is printing the following:

the value of number is 0.00

What is the error in the code?

#include <stdio.h>

int main(){  
    float numero;
    numero = 1/3;
    printf("o valor do numero e' de :%4.2f \n\n", numero );
    return 0;
}

Answer:

Because the code is dividing an integer by another integer.

Used a literal number which is an integer value. When you consider only whole numbers, dividing 1 by 3 gives 0 anyway. After the calculation results in zero, it is converted to float by the automatic casting rule. But note that this casting only occurs with the result as a whole and not with each operand individually.

#include <stdio.h>

int main() {
    printf("o valor do numero e': %4.2f", 1.0f/3.0f);
}

See it working on ideone . And on repl.it. I also put it on GitHub for future reference .

Using the numeric literal for the floating point type (1.0f for example) the division takes place correctly.

Scroll to Top