Why is the result of this operation resulting in an integer and not a "float"?

Asked

Viewed 73 times

0

Because the result of the algorithm below is 1, and it should be 1.83?

#include <stdio.h>

int main() {
    float y; 
    y = 1 + (1 / 2) + (1/3);
    printf("o resultado é %f" , y);
    return 0;
}
  • 1

    Try typing numbers with decimal (example, 1.0 instead of 1). As you see it, the language is interpreting the numbers as integers rather than floating points. It will only convert to float when saving the value in y after having already made all calculations with integers, consequently resulting in 1.

  • I did it and it worked! Thank you very much for the explanation.

1 answer

2

Even if you define the y as float, the division numbers are whole, soon the compiler C++ assumes that the result will also be integer.

As @Leafar said, for him to perform the division decimal, you have to show that the numbers are decimal.

One of the ways to accomplish this is to add a .0f in each number of the operation.

The code would look like this:

#include <stdio.h>

int main()
{
    float y;
    y = 1.0f + (1.0f/2.0f) + (1.0f/3.0f);
    printf("o resultado é %f", y);
    return 0;
}

(Note: it is not necessary to put the .0f in all, just us 1/ would be enough).

Useful links for reference:

Maniero’s answer to another question

Reference of the website cplusplus about casting

  • I did it and it worked! Thank you very much for the explanation.

Browser other questions tagged

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