Double to Int

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Prosdo
    New Member
    • Nov 2007
    • 32

    #1

    Double to Int

    Hi guys. I e-mailed my teacher about this a couple days ago and he hasn't gotten back to me. If I am dealing with a double and I want to convert it to an int is there a certain command I use? Because I am getting errors.

    The program calls for roofing squares and if it has any decimal points the teacher said round up. He said just turn it to an int and add 1. The problem is I am getting errors. Thank you.
  • sicarie
    Recognized Expert Specialist
    • Nov 2006
    • 4677

    #2
    Well, you don't mention if you are using C or C++, but if you are using C++, I would recommend using stringstreams. Otherwise, you'll have to debug your error messages. If you post them here, we can try to help.

    Comment

    • Prosdo
      New Member
      • Nov 2007
      • 32

      #3
      Originally posted by sicarie
      Well, you don't mention if you are using C or C++, but if you are using C++, I would recommend using stringstreams. Otherwise, you'll have to debug your error messages. If you post them here, we can try to help.
      I fixed it with a static cast. Thank you though.

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        There, you said it yourself: I fixed it with a cast.

        Any cast in C++ means you are overriding the compiler's enforcement of the rules of the language and are going into the weeds. That is, a cast says to the compiler: Shut up! and do what I tell ya!!

        You cannot convert a double to an int. An int has no decimal portion so you would lose part of your data. The cast was just a meat-axe that chopped off the decimals.

        The larger issue is why this ocurred. Generally, floating point is used for scientific applications where extreme accuracy is not required and is not supposed to be mixed with the integer family of variables. That is, your code should either use double throughout or should use integers throughout but not a mixture of the two.

        Comment

        Working...