This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

math question (beginner)

I'm using float variables, but I want to convert these variables to integer


like: 0.9 .... 1
30.9 .... 31
54.2 .... 54


please give a suggestion

thanks very much

Parents
  • The compiler will do the conversion for you when you do an assignment. Just assign a float to an integer.

    For rounding, the easiest thing to do is always add 0.5 to the float. It will take more time and code space to check whether you need to do so than it does just to add 0.5 and have it truncated away again.

    i = f; // truncate
    i = f + 0.5; // round

    At some point you might be interested in the floor() and ceil() functions in math.h.

Reply
  • The compiler will do the conversion for you when you do an assignment. Just assign a float to an integer.

    For rounding, the easiest thing to do is always add 0.5 to the float. It will take more time and code space to check whether you need to do so than it does just to add 0.5 and have it truncated away again.

    i = f; // truncate
    i = f + 0.5; // round

    At some point you might be interested in the floor() and ceil() functions in math.h.

Children