# Split result gives zero in the decimal places

7

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

the value of number e 'of 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;
}
``````

asked by anonymous 10.12.2014 / 23:31

10

Because the code is dividing an integer by another integer.

Used a literal number that is an integer value. When you consider only integers, the division of 1 by 3 gives the same number. 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 on each operand individually.

``````#include <stdio.h>

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

See running on ideone . And no Coding Ground . Also I put GitHub for future reference .

Using the numeric literal for the floating-point type (1.0f for example), the division occurs correctly.

10.12.2014 / 23:49
7

The problem is that the expression `1/3` is evaluated in the context of integers. In an integer division, `1/3 == 0` (expression is evaluated before being assigned to variable `numero` ).

If you use a `float` value in your division then you will have the value you expect, as in the example below:

``````#include <stdio.h>

int main(){

float numero;

numero = 1.0f/3;

printf("o valor do numero e':%4.2f \n\n", numero );

return 0;
}
``````

10.12.2014 / 23:48
1
``````#include <stdio.h>

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

01.02.2016 / 04:06