Split result equals zero in decimals

Asked

Viewed 4,910 times

9

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

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;
}
  • Take a look at [tour]. You can accept an answer if it solved your problem. You can vote on every post on the site as well. Did any help you more? You need something to be improved?

  • Always prefer (*) to use double instead of float. (*) except when the teacher keeps insisting after you explain to him the advantages of double (is the only descantagem that does not make sense in "programetas").

3 answers

12

Because the code is dividing an integer by an integer.

You used a literal number which is an integer value. When you consider only integers, the division of 1 by 3 gives 0 the same. After the calculation results in zero, it is converted to float by the rule of casting automatic. But note that this casting only occurs with the result as a whole and not in each individual operand.

#include <stdio.h>

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

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Using the numeric literal for the floating point type (1.0f for example), the division occurs in the correct way.

8

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

If you use a value float 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;
}

2

#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;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.