Why does dividing two int not yield the right value when assigned to double?Dividing two integers to produce a float resultCan't get cout to display decimals c++Why does 1 / 10 equal zero unless I use variables?Issue with fahrenheit conversion formula in CRandom number between zero and one in c++Variable values don't change in for loopLog calls return NaN in CEstimating pi with c++ for loopWhy doesn't my function return a float?cout printing integer when expecting float(double)How to nicely format floating numbers to String without unnecessary decimal 0?JavaScript OR (||) variable assignment explanationC++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?converting double to integer in javaWhy should C++ programmers minimize use of 'new'?Image Processing: Algorithm Improvement for 'Coca-Cola Can' RecognitionValue changing when converting from double to intDouble always returns 0 when dividing intsWhy should I use a pointer rather than the object itself?Replacing a 32-bit loop counter with 64-bit introduces crazy performance deviations

A ring of generalized power series

Chilling water in copper vessel

Why do people prefer metropolitan areas, considering monsters and villains?

Publishing papers seem natural to many, while I find it really hard to think novel stuff to pursue till publication. How to cope up with this?

Can Jimmy hang on his rope?

Can the word "desk" be used as a verb?

QR codes, do people use them?

Gory anime with pink haired girl escaping an asylum

What are the consequences for a developed nation to not accept any refugees?

Why won't the U.S. sign a peace treaty with North Korea?

How do I explain that I don't want to maintain old projects?

How to understand flavors and when to use combination of them?

How do I talk to my wife about unrealistic expectations?

How to slice a string input at a certain unknown index

When do flights get cancelled due to fog?

Is there a method for differentiating informative comments from commented out code?

Deck of Cards with Shuffle and Sort functionality

Was it ever illegal to name a pig "Napoleon" in France?

Sense of humor in your sci-fi stories

Is it possible to complete a PhD in CS in 3 years?

How to "extend" classes in Haskell

Who goes first? Person disembarking bus or the bicycle?

How does one acquire an undead eyeball encased in a gem?

How to use Adostop Eco stop bath?



Why does dividing two int not yield the right value when assigned to double?


Dividing two integers to produce a float resultCan't get cout to display decimals c++Why does 1 / 10 equal zero unless I use variables?Issue with fahrenheit conversion formula in CRandom number between zero and one in c++Variable values don't change in for loopLog calls return NaN in CEstimating pi with c++ for loopWhy doesn't my function return a float?cout printing integer when expecting float(double)How to nicely format floating numbers to String without unnecessary decimal 0?JavaScript OR (||) variable assignment explanationC++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?converting double to integer in javaWhy should C++ programmers minimize use of 'new'?Image Processing: Algorithm Improvement for 'Coca-Cola Can' RecognitionValue changing when converting from double to intDouble always returns 0 when dividing intsWhy should I use a pointer rather than the object itself?Replacing a 32-bit loop counter with 64-bit introduces crazy performance deviations






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








90















How come that in the following snippet



int a = 7;
int b = 3;
double c = 0;
c = a / b;


c ends up having the value 2, rather than 2.3333, as one would expect. If a and b are doubles, the answer does turn to 2.333. But surely because c already is a double it should have worked with integers?



So how come int/int=double doesn't work?










share|improve this question
























  • Possible duplicate of Division result is always zero

    – phuclv
    Sep 9 '18 at 4:51

















90















How come that in the following snippet



int a = 7;
int b = 3;
double c = 0;
c = a / b;


c ends up having the value 2, rather than 2.3333, as one would expect. If a and b are doubles, the answer does turn to 2.333. But surely because c already is a double it should have worked with integers?



So how come int/int=double doesn't work?










share|improve this question
























  • Possible duplicate of Division result is always zero

    – phuclv
    Sep 9 '18 at 4:51













90












90








90


17






How come that in the following snippet



int a = 7;
int b = 3;
double c = 0;
c = a / b;


c ends up having the value 2, rather than 2.3333, as one would expect. If a and b are doubles, the answer does turn to 2.333. But surely because c already is a double it should have worked with integers?



So how come int/int=double doesn't work?










share|improve this question
















How come that in the following snippet



int a = 7;
int b = 3;
double c = 0;
c = a / b;


c ends up having the value 2, rather than 2.3333, as one would expect. If a and b are doubles, the answer does turn to 2.333. But surely because c already is a double it should have worked with integers?



So how come int/int=double doesn't work?







c++ variables double integer-division






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 15 '17 at 13:05









Baum mit Augen

42.2k12 gold badges122 silver badges156 bronze badges




42.2k12 gold badges122 silver badges156 bronze badges










asked Sep 27 '11 at 15:02









JahoeJahoe

6021 gold badge6 silver badges26 bronze badges




6021 gold badge6 silver badges26 bronze badges












  • Possible duplicate of Division result is always zero

    – phuclv
    Sep 9 '18 at 4:51

















  • Possible duplicate of Division result is always zero

    – phuclv
    Sep 9 '18 at 4:51
















Possible duplicate of Division result is always zero

– phuclv
Sep 9 '18 at 4:51





Possible duplicate of Division result is always zero

– phuclv
Sep 9 '18 at 4:51












8 Answers
8






active

oldest

votes


















142














This is because you are using the integer division version of operator/, which takes 2 ints and returns an int. In order to use the double version, which returns a double, at least one of the ints must be explicitly casted to a double.



c = a/(double)b;





share|improve this answer


















  • 9





    I would prefer to explicitly convert both a and b to double simply for clarity, but it really doesn't matter.

    – John Dibling
    Sep 27 '11 at 15:31







  • 24





    Since the question is tagged C++ I would prefer to see static_cast<> rather than a C cast.

    – Martin York
    Sep 27 '11 at 15:41






  • 15





    Personally, I feel that the C style casts are clearer (casting in most other common languages is done in the C style way). static_cast<> always seemed long winded to me. In the case of primitives, there is not really any danger of getting static_cast<> and reinterpret_cast<> mixed up.

    – Chad La Guardia
    Sep 27 '11 at 15:47






  • 6





    @Tux-D: For arithmetic casts? I would prefer to avoid static_cast in this case and use C-style cast instead. There's no benefit in using C++-style casts here and they clutter the code a lot more than C-style casts. Arithmetic cast is exactly the context where C-style casts are perfectly appropriate and actually more appropriate than other casts.

    – AnT
    Sep 27 '11 at 16:14







  • 18





    Sometimes you can outwit the "no C-style-cast" folks by writing double(b). They don't always realise that it's a conversion, since it looks the same as an explicit constructor call.

    – Steve Jessop
    Sep 27 '11 at 16:26


















11














Here it is:



a) Dividing two ints performs integer division always. So the result of a/b in your case can only be an int.



If you want to keep a and b as ints, yet divide them fully, you must cast at least one of them to double: (double)a/b or a/(double)b or (double)a/(double)b.



b) c is a double, so it can accept an int value on assignement: the int is automatically converted to double and assigned to c.



c) Remember that on assignement, the expression to the right of = is computed first (according to rule (a) above, and without regard of the variable to the left of =) and then assigned to the variable to the left of = (according to (b) above). I believe this completes the picture.






share|improve this answer






























    9














    With very few exceptions (I can only think of one), C++ determines the
    entire meaning of an expression (or sub-expression) from the expression
    itself. What you do with the results of the expression doesn't matter.
    In your case, in the expression a / b, there's not a double in
    sight; everything is int. So the compiler uses integer division.
    Only once it has the result does it consider what to do with it, and
    convert it to double.






    share|improve this answer


















    • 2





      The one exception I can think of is choosing a function overload when taking a pointer - the value of &funcname depends what type you cast it to.

      – Steve Jessop
      Sep 27 '11 at 15:44







    • 1





      @Steve Jessop That's the only exception I can think of as well. (But given the size and complexity of the standard, I wouldn't like to swear that I haven't missed any.)

      – James Kanze
      Sep 27 '11 at 16:01


















    6














    When you divide two integers, the result will be an integer, irrespective of the fact that you store it in a double.






    share|improve this answer






























      5














      c is a double variable, but the value being assigned to it is an int value because it results from the division of two ints, which gives you "integer division" (dropping the remainder). So what happens in the line c=a/b is




      1. a/b is evaluated, creating a temporary of type int

      2. the value of the temporary is assigned to c after conversion to type double.

      The value of a/b is determined without reference to its context (assignment to double).






      share|improve this answer






























        4














        The / operator can be used for integer division or floating point division. You're giving it two integer operands, so it's doing integer division and then the result is being stored in a double.






        share|improve this answer






























          4














          In C++ language the result of the subexpresison is never affected by the surrounding context (with some rare exceptions). This is one of the principles that the language carefully follows. The expression c = a / b contains of an independent subexpression a / b, which is interpreted independently from anything outside that subexpression. The language does not care that you later will assign the result to a double. a / b is an integer division. Anything else does not matter. You will see this principle followed in many corners of the language specification. That's juts how C++ (and C) works.



          One example of an exception I mentioned above is the function pointer assignment/initialization in situations with function overloading



          void foo(int);
          void foo(double);

          void (*p)(double) = &foo; // automatically selects `foo(fouble)`


          This is one context where the left-hand side of an assignment/initialization affects the behavior of the right-hand side. (Also, reference-to-array initialization prevents array type decay, which is another example of similar behavior.) In all other cases the right-hand side completely ignores the left-hand side.






          share|improve this answer






























            2














            This is technically a language-dependent, but almost all languages treat this subject the same. When there is a type mismatch between two data types in an expression, most languages will try to cast the data on one side of the = to match the data on the other side according to a set of predefined rules.



            When dividing two numbers of the same type (integers, doubles, etc.) the result will always be of the same type (so 'int/int' will always result in int).



            In this case you have
            double var = integer result
            which casts the integer result to a double after the calculation in which case the fractional data is already lost. (most languages will do this casting to prevent type inaccuracies without raising an exception or error).



            If you'd like to keep the result as a double you're going to want to create a situation where you have
            double var = double result



            The easiest way to do that is to force the expression on the right side of an equation to cast to double:



            c = a/(double)b



            Division between an integer and a double will result in casting the integer to the double (note that when doing maths, the compiler will often "upcast" to the most specific data type this is to prevent data loss).



            After the upcast, a will wind up as a double and now you have division between two doubles. This will create the desired division and assignment.



            AGAIN, please note that this is language specific (and can even be compiler specific), however almost all languages (certainly all the ones I can think of off the top of my head) treat this example identically.






            share|improve this answer

























            • This question is tagged [C++], and the C++ Standard dictates exactly how this works. Not sure what you mean by "language specific" and it's certainly not compiler-specific, assuming no compiler extenstions are engaged.

              – John Dibling
              Sep 27 '11 at 15:32












            • Also it's incorrect to say that "double var = integer result which casts the double var down to int". The double isn't cast to an int. The int result is converted to a double.

              – John Dibling
              Sep 27 '11 at 15:35











            • I was allowing for the possibility of compiler extensions (I've actually had this issue once where my environment was "mis-casting" the results and I couldn't figure out why). And the result is language specific as in some languages don't follow the same casting rules. I didn't consider that it was a C++ specific tag. You're right about the "double var = integer result" comment. Edited to reflect that. Thank you!

              – matthewdunnam
              Sep 27 '11 at 20:18














            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f7571326%2fwhy-does-dividing-two-int-not-yield-the-right-value-when-assigned-to-double%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            8 Answers
            8






            active

            oldest

            votes








            8 Answers
            8






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            142














            This is because you are using the integer division version of operator/, which takes 2 ints and returns an int. In order to use the double version, which returns a double, at least one of the ints must be explicitly casted to a double.



            c = a/(double)b;





            share|improve this answer


















            • 9





              I would prefer to explicitly convert both a and b to double simply for clarity, but it really doesn't matter.

              – John Dibling
              Sep 27 '11 at 15:31







            • 24





              Since the question is tagged C++ I would prefer to see static_cast<> rather than a C cast.

              – Martin York
              Sep 27 '11 at 15:41






            • 15





              Personally, I feel that the C style casts are clearer (casting in most other common languages is done in the C style way). static_cast<> always seemed long winded to me. In the case of primitives, there is not really any danger of getting static_cast<> and reinterpret_cast<> mixed up.

              – Chad La Guardia
              Sep 27 '11 at 15:47






            • 6





              @Tux-D: For arithmetic casts? I would prefer to avoid static_cast in this case and use C-style cast instead. There's no benefit in using C++-style casts here and they clutter the code a lot more than C-style casts. Arithmetic cast is exactly the context where C-style casts are perfectly appropriate and actually more appropriate than other casts.

              – AnT
              Sep 27 '11 at 16:14







            • 18





              Sometimes you can outwit the "no C-style-cast" folks by writing double(b). They don't always realise that it's a conversion, since it looks the same as an explicit constructor call.

              – Steve Jessop
              Sep 27 '11 at 16:26















            142














            This is because you are using the integer division version of operator/, which takes 2 ints and returns an int. In order to use the double version, which returns a double, at least one of the ints must be explicitly casted to a double.



            c = a/(double)b;





            share|improve this answer


















            • 9





              I would prefer to explicitly convert both a and b to double simply for clarity, but it really doesn't matter.

              – John Dibling
              Sep 27 '11 at 15:31







            • 24





              Since the question is tagged C++ I would prefer to see static_cast<> rather than a C cast.

              – Martin York
              Sep 27 '11 at 15:41






            • 15





              Personally, I feel that the C style casts are clearer (casting in most other common languages is done in the C style way). static_cast<> always seemed long winded to me. In the case of primitives, there is not really any danger of getting static_cast<> and reinterpret_cast<> mixed up.

              – Chad La Guardia
              Sep 27 '11 at 15:47






            • 6





              @Tux-D: For arithmetic casts? I would prefer to avoid static_cast in this case and use C-style cast instead. There's no benefit in using C++-style casts here and they clutter the code a lot more than C-style casts. Arithmetic cast is exactly the context where C-style casts are perfectly appropriate and actually more appropriate than other casts.

              – AnT
              Sep 27 '11 at 16:14







            • 18





              Sometimes you can outwit the "no C-style-cast" folks by writing double(b). They don't always realise that it's a conversion, since it looks the same as an explicit constructor call.

              – Steve Jessop
              Sep 27 '11 at 16:26













            142












            142








            142







            This is because you are using the integer division version of operator/, which takes 2 ints and returns an int. In order to use the double version, which returns a double, at least one of the ints must be explicitly casted to a double.



            c = a/(double)b;





            share|improve this answer













            This is because you are using the integer division version of operator/, which takes 2 ints and returns an int. In order to use the double version, which returns a double, at least one of the ints must be explicitly casted to a double.



            c = a/(double)b;






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Sep 27 '11 at 15:05









            Chad La GuardiaChad La Guardia

            4,0283 gold badges20 silver badges33 bronze badges




            4,0283 gold badges20 silver badges33 bronze badges







            • 9





              I would prefer to explicitly convert both a and b to double simply for clarity, but it really doesn't matter.

              – John Dibling
              Sep 27 '11 at 15:31







            • 24





              Since the question is tagged C++ I would prefer to see static_cast<> rather than a C cast.

              – Martin York
              Sep 27 '11 at 15:41






            • 15





              Personally, I feel that the C style casts are clearer (casting in most other common languages is done in the C style way). static_cast<> always seemed long winded to me. In the case of primitives, there is not really any danger of getting static_cast<> and reinterpret_cast<> mixed up.

              – Chad La Guardia
              Sep 27 '11 at 15:47






            • 6





              @Tux-D: For arithmetic casts? I would prefer to avoid static_cast in this case and use C-style cast instead. There's no benefit in using C++-style casts here and they clutter the code a lot more than C-style casts. Arithmetic cast is exactly the context where C-style casts are perfectly appropriate and actually more appropriate than other casts.

              – AnT
              Sep 27 '11 at 16:14







            • 18





              Sometimes you can outwit the "no C-style-cast" folks by writing double(b). They don't always realise that it's a conversion, since it looks the same as an explicit constructor call.

              – Steve Jessop
              Sep 27 '11 at 16:26












            • 9





              I would prefer to explicitly convert both a and b to double simply for clarity, but it really doesn't matter.

              – John Dibling
              Sep 27 '11 at 15:31







            • 24





              Since the question is tagged C++ I would prefer to see static_cast<> rather than a C cast.

              – Martin York
              Sep 27 '11 at 15:41






            • 15





              Personally, I feel that the C style casts are clearer (casting in most other common languages is done in the C style way). static_cast<> always seemed long winded to me. In the case of primitives, there is not really any danger of getting static_cast<> and reinterpret_cast<> mixed up.

              – Chad La Guardia
              Sep 27 '11 at 15:47






            • 6





              @Tux-D: For arithmetic casts? I would prefer to avoid static_cast in this case and use C-style cast instead. There's no benefit in using C++-style casts here and they clutter the code a lot more than C-style casts. Arithmetic cast is exactly the context where C-style casts are perfectly appropriate and actually more appropriate than other casts.

              – AnT
              Sep 27 '11 at 16:14







            • 18





              Sometimes you can outwit the "no C-style-cast" folks by writing double(b). They don't always realise that it's a conversion, since it looks the same as an explicit constructor call.

              – Steve Jessop
              Sep 27 '11 at 16:26







            9




            9





            I would prefer to explicitly convert both a and b to double simply for clarity, but it really doesn't matter.

            – John Dibling
            Sep 27 '11 at 15:31






            I would prefer to explicitly convert both a and b to double simply for clarity, but it really doesn't matter.

            – John Dibling
            Sep 27 '11 at 15:31





            24




            24





            Since the question is tagged C++ I would prefer to see static_cast<> rather than a C cast.

            – Martin York
            Sep 27 '11 at 15:41





            Since the question is tagged C++ I would prefer to see static_cast<> rather than a C cast.

            – Martin York
            Sep 27 '11 at 15:41




            15




            15





            Personally, I feel that the C style casts are clearer (casting in most other common languages is done in the C style way). static_cast<> always seemed long winded to me. In the case of primitives, there is not really any danger of getting static_cast<> and reinterpret_cast<> mixed up.

            – Chad La Guardia
            Sep 27 '11 at 15:47





            Personally, I feel that the C style casts are clearer (casting in most other common languages is done in the C style way). static_cast<> always seemed long winded to me. In the case of primitives, there is not really any danger of getting static_cast<> and reinterpret_cast<> mixed up.

            – Chad La Guardia
            Sep 27 '11 at 15:47




            6




            6





            @Tux-D: For arithmetic casts? I would prefer to avoid static_cast in this case and use C-style cast instead. There's no benefit in using C++-style casts here and they clutter the code a lot more than C-style casts. Arithmetic cast is exactly the context where C-style casts are perfectly appropriate and actually more appropriate than other casts.

            – AnT
            Sep 27 '11 at 16:14






            @Tux-D: For arithmetic casts? I would prefer to avoid static_cast in this case and use C-style cast instead. There's no benefit in using C++-style casts here and they clutter the code a lot more than C-style casts. Arithmetic cast is exactly the context where C-style casts are perfectly appropriate and actually more appropriate than other casts.

            – AnT
            Sep 27 '11 at 16:14





            18




            18





            Sometimes you can outwit the "no C-style-cast" folks by writing double(b). They don't always realise that it's a conversion, since it looks the same as an explicit constructor call.

            – Steve Jessop
            Sep 27 '11 at 16:26





            Sometimes you can outwit the "no C-style-cast" folks by writing double(b). They don't always realise that it's a conversion, since it looks the same as an explicit constructor call.

            – Steve Jessop
            Sep 27 '11 at 16:26













            11














            Here it is:



            a) Dividing two ints performs integer division always. So the result of a/b in your case can only be an int.



            If you want to keep a and b as ints, yet divide them fully, you must cast at least one of them to double: (double)a/b or a/(double)b or (double)a/(double)b.



            b) c is a double, so it can accept an int value on assignement: the int is automatically converted to double and assigned to c.



            c) Remember that on assignement, the expression to the right of = is computed first (according to rule (a) above, and without regard of the variable to the left of =) and then assigned to the variable to the left of = (according to (b) above). I believe this completes the picture.






            share|improve this answer



























              11














              Here it is:



              a) Dividing two ints performs integer division always. So the result of a/b in your case can only be an int.



              If you want to keep a and b as ints, yet divide them fully, you must cast at least one of them to double: (double)a/b or a/(double)b or (double)a/(double)b.



              b) c is a double, so it can accept an int value on assignement: the int is automatically converted to double and assigned to c.



              c) Remember that on assignement, the expression to the right of = is computed first (according to rule (a) above, and without regard of the variable to the left of =) and then assigned to the variable to the left of = (according to (b) above). I believe this completes the picture.






              share|improve this answer

























                11












                11








                11







                Here it is:



                a) Dividing two ints performs integer division always. So the result of a/b in your case can only be an int.



                If you want to keep a and b as ints, yet divide them fully, you must cast at least one of them to double: (double)a/b or a/(double)b or (double)a/(double)b.



                b) c is a double, so it can accept an int value on assignement: the int is automatically converted to double and assigned to c.



                c) Remember that on assignement, the expression to the right of = is computed first (according to rule (a) above, and without regard of the variable to the left of =) and then assigned to the variable to the left of = (according to (b) above). I believe this completes the picture.






                share|improve this answer













                Here it is:



                a) Dividing two ints performs integer division always. So the result of a/b in your case can only be an int.



                If you want to keep a and b as ints, yet divide them fully, you must cast at least one of them to double: (double)a/b or a/(double)b or (double)a/(double)b.



                b) c is a double, so it can accept an int value on assignement: the int is automatically converted to double and assigned to c.



                c) Remember that on assignement, the expression to the right of = is computed first (according to rule (a) above, and without regard of the variable to the left of =) and then assigned to the variable to the left of = (according to (b) above). I believe this completes the picture.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Sep 27 '11 at 15:15









                nplatisnplatis

                3671 silver badge8 bronze badges




                3671 silver badge8 bronze badges





















                    9














                    With very few exceptions (I can only think of one), C++ determines the
                    entire meaning of an expression (or sub-expression) from the expression
                    itself. What you do with the results of the expression doesn't matter.
                    In your case, in the expression a / b, there's not a double in
                    sight; everything is int. So the compiler uses integer division.
                    Only once it has the result does it consider what to do with it, and
                    convert it to double.






                    share|improve this answer


















                    • 2





                      The one exception I can think of is choosing a function overload when taking a pointer - the value of &funcname depends what type you cast it to.

                      – Steve Jessop
                      Sep 27 '11 at 15:44







                    • 1





                      @Steve Jessop That's the only exception I can think of as well. (But given the size and complexity of the standard, I wouldn't like to swear that I haven't missed any.)

                      – James Kanze
                      Sep 27 '11 at 16:01















                    9














                    With very few exceptions (I can only think of one), C++ determines the
                    entire meaning of an expression (or sub-expression) from the expression
                    itself. What you do with the results of the expression doesn't matter.
                    In your case, in the expression a / b, there's not a double in
                    sight; everything is int. So the compiler uses integer division.
                    Only once it has the result does it consider what to do with it, and
                    convert it to double.






                    share|improve this answer


















                    • 2





                      The one exception I can think of is choosing a function overload when taking a pointer - the value of &funcname depends what type you cast it to.

                      – Steve Jessop
                      Sep 27 '11 at 15:44







                    • 1





                      @Steve Jessop That's the only exception I can think of as well. (But given the size and complexity of the standard, I wouldn't like to swear that I haven't missed any.)

                      – James Kanze
                      Sep 27 '11 at 16:01













                    9












                    9








                    9







                    With very few exceptions (I can only think of one), C++ determines the
                    entire meaning of an expression (or sub-expression) from the expression
                    itself. What you do with the results of the expression doesn't matter.
                    In your case, in the expression a / b, there's not a double in
                    sight; everything is int. So the compiler uses integer division.
                    Only once it has the result does it consider what to do with it, and
                    convert it to double.






                    share|improve this answer













                    With very few exceptions (I can only think of one), C++ determines the
                    entire meaning of an expression (or sub-expression) from the expression
                    itself. What you do with the results of the expression doesn't matter.
                    In your case, in the expression a / b, there's not a double in
                    sight; everything is int. So the compiler uses integer division.
                    Only once it has the result does it consider what to do with it, and
                    convert it to double.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Sep 27 '11 at 15:11









                    James KanzeJames Kanze

                    132k12 gold badges145 silver badges286 bronze badges




                    132k12 gold badges145 silver badges286 bronze badges







                    • 2





                      The one exception I can think of is choosing a function overload when taking a pointer - the value of &funcname depends what type you cast it to.

                      – Steve Jessop
                      Sep 27 '11 at 15:44







                    • 1





                      @Steve Jessop That's the only exception I can think of as well. (But given the size and complexity of the standard, I wouldn't like to swear that I haven't missed any.)

                      – James Kanze
                      Sep 27 '11 at 16:01












                    • 2





                      The one exception I can think of is choosing a function overload when taking a pointer - the value of &funcname depends what type you cast it to.

                      – Steve Jessop
                      Sep 27 '11 at 15:44







                    • 1





                      @Steve Jessop That's the only exception I can think of as well. (But given the size and complexity of the standard, I wouldn't like to swear that I haven't missed any.)

                      – James Kanze
                      Sep 27 '11 at 16:01







                    2




                    2





                    The one exception I can think of is choosing a function overload when taking a pointer - the value of &funcname depends what type you cast it to.

                    – Steve Jessop
                    Sep 27 '11 at 15:44






                    The one exception I can think of is choosing a function overload when taking a pointer - the value of &funcname depends what type you cast it to.

                    – Steve Jessop
                    Sep 27 '11 at 15:44





                    1




                    1





                    @Steve Jessop That's the only exception I can think of as well. (But given the size and complexity of the standard, I wouldn't like to swear that I haven't missed any.)

                    – James Kanze
                    Sep 27 '11 at 16:01





                    @Steve Jessop That's the only exception I can think of as well. (But given the size and complexity of the standard, I wouldn't like to swear that I haven't missed any.)

                    – James Kanze
                    Sep 27 '11 at 16:01











                    6














                    When you divide two integers, the result will be an integer, irrespective of the fact that you store it in a double.






                    share|improve this answer



























                      6














                      When you divide two integers, the result will be an integer, irrespective of the fact that you store it in a double.






                      share|improve this answer

























                        6












                        6








                        6







                        When you divide two integers, the result will be an integer, irrespective of the fact that you store it in a double.






                        share|improve this answer













                        When you divide two integers, the result will be an integer, irrespective of the fact that you store it in a double.







                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Sep 27 '11 at 15:06









                        Alok SaveAlok Save

                        168k37 gold badges358 silver badges491 bronze badges




                        168k37 gold badges358 silver badges491 bronze badges





















                            5














                            c is a double variable, but the value being assigned to it is an int value because it results from the division of two ints, which gives you "integer division" (dropping the remainder). So what happens in the line c=a/b is




                            1. a/b is evaluated, creating a temporary of type int

                            2. the value of the temporary is assigned to c after conversion to type double.

                            The value of a/b is determined without reference to its context (assignment to double).






                            share|improve this answer



























                              5














                              c is a double variable, but the value being assigned to it is an int value because it results from the division of two ints, which gives you "integer division" (dropping the remainder). So what happens in the line c=a/b is




                              1. a/b is evaluated, creating a temporary of type int

                              2. the value of the temporary is assigned to c after conversion to type double.

                              The value of a/b is determined without reference to its context (assignment to double).






                              share|improve this answer

























                                5












                                5








                                5







                                c is a double variable, but the value being assigned to it is an int value because it results from the division of two ints, which gives you "integer division" (dropping the remainder). So what happens in the line c=a/b is




                                1. a/b is evaluated, creating a temporary of type int

                                2. the value of the temporary is assigned to c after conversion to type double.

                                The value of a/b is determined without reference to its context (assignment to double).






                                share|improve this answer













                                c is a double variable, but the value being assigned to it is an int value because it results from the division of two ints, which gives you "integer division" (dropping the remainder). So what happens in the line c=a/b is




                                1. a/b is evaluated, creating a temporary of type int

                                2. the value of the temporary is assigned to c after conversion to type double.

                                The value of a/b is determined without reference to its context (assignment to double).







                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Sep 27 '11 at 15:04









                                Fred FooFred Foo

                                288k59 gold badges611 silver badges741 bronze badges




                                288k59 gold badges611 silver badges741 bronze badges





















                                    4














                                    The / operator can be used for integer division or floating point division. You're giving it two integer operands, so it's doing integer division and then the result is being stored in a double.






                                    share|improve this answer



























                                      4














                                      The / operator can be used for integer division or floating point division. You're giving it two integer operands, so it's doing integer division and then the result is being stored in a double.






                                      share|improve this answer

























                                        4












                                        4








                                        4







                                        The / operator can be used for integer division or floating point division. You're giving it two integer operands, so it's doing integer division and then the result is being stored in a double.






                                        share|improve this answer













                                        The / operator can be used for integer division or floating point division. You're giving it two integer operands, so it's doing integer division and then the result is being stored in a double.







                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered Sep 27 '11 at 15:07









                                        VickyVicky

                                        10.9k2 gold badges41 silver badges49 bronze badges




                                        10.9k2 gold badges41 silver badges49 bronze badges





















                                            4














                                            In C++ language the result of the subexpresison is never affected by the surrounding context (with some rare exceptions). This is one of the principles that the language carefully follows. The expression c = a / b contains of an independent subexpression a / b, which is interpreted independently from anything outside that subexpression. The language does not care that you later will assign the result to a double. a / b is an integer division. Anything else does not matter. You will see this principle followed in many corners of the language specification. That's juts how C++ (and C) works.



                                            One example of an exception I mentioned above is the function pointer assignment/initialization in situations with function overloading



                                            void foo(int);
                                            void foo(double);

                                            void (*p)(double) = &foo; // automatically selects `foo(fouble)`


                                            This is one context where the left-hand side of an assignment/initialization affects the behavior of the right-hand side. (Also, reference-to-array initialization prevents array type decay, which is another example of similar behavior.) In all other cases the right-hand side completely ignores the left-hand side.






                                            share|improve this answer



























                                              4














                                              In C++ language the result of the subexpresison is never affected by the surrounding context (with some rare exceptions). This is one of the principles that the language carefully follows. The expression c = a / b contains of an independent subexpression a / b, which is interpreted independently from anything outside that subexpression. The language does not care that you later will assign the result to a double. a / b is an integer division. Anything else does not matter. You will see this principle followed in many corners of the language specification. That's juts how C++ (and C) works.



                                              One example of an exception I mentioned above is the function pointer assignment/initialization in situations with function overloading



                                              void foo(int);
                                              void foo(double);

                                              void (*p)(double) = &foo; // automatically selects `foo(fouble)`


                                              This is one context where the left-hand side of an assignment/initialization affects the behavior of the right-hand side. (Also, reference-to-array initialization prevents array type decay, which is another example of similar behavior.) In all other cases the right-hand side completely ignores the left-hand side.






                                              share|improve this answer

























                                                4












                                                4








                                                4







                                                In C++ language the result of the subexpresison is never affected by the surrounding context (with some rare exceptions). This is one of the principles that the language carefully follows. The expression c = a / b contains of an independent subexpression a / b, which is interpreted independently from anything outside that subexpression. The language does not care that you later will assign the result to a double. a / b is an integer division. Anything else does not matter. You will see this principle followed in many corners of the language specification. That's juts how C++ (and C) works.



                                                One example of an exception I mentioned above is the function pointer assignment/initialization in situations with function overloading



                                                void foo(int);
                                                void foo(double);

                                                void (*p)(double) = &foo; // automatically selects `foo(fouble)`


                                                This is one context where the left-hand side of an assignment/initialization affects the behavior of the right-hand side. (Also, reference-to-array initialization prevents array type decay, which is another example of similar behavior.) In all other cases the right-hand side completely ignores the left-hand side.






                                                share|improve this answer













                                                In C++ language the result of the subexpresison is never affected by the surrounding context (with some rare exceptions). This is one of the principles that the language carefully follows. The expression c = a / b contains of an independent subexpression a / b, which is interpreted independently from anything outside that subexpression. The language does not care that you later will assign the result to a double. a / b is an integer division. Anything else does not matter. You will see this principle followed in many corners of the language specification. That's juts how C++ (and C) works.



                                                One example of an exception I mentioned above is the function pointer assignment/initialization in situations with function overloading



                                                void foo(int);
                                                void foo(double);

                                                void (*p)(double) = &foo; // automatically selects `foo(fouble)`


                                                This is one context where the left-hand side of an assignment/initialization affects the behavior of the right-hand side. (Also, reference-to-array initialization prevents array type decay, which is another example of similar behavior.) In all other cases the right-hand side completely ignores the left-hand side.







                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Sep 27 '11 at 16:20









                                                AnTAnT

                                                265k35 gold badges431 silver badges674 bronze badges




                                                265k35 gold badges431 silver badges674 bronze badges





















                                                    2














                                                    This is technically a language-dependent, but almost all languages treat this subject the same. When there is a type mismatch between two data types in an expression, most languages will try to cast the data on one side of the = to match the data on the other side according to a set of predefined rules.



                                                    When dividing two numbers of the same type (integers, doubles, etc.) the result will always be of the same type (so 'int/int' will always result in int).



                                                    In this case you have
                                                    double var = integer result
                                                    which casts the integer result to a double after the calculation in which case the fractional data is already lost. (most languages will do this casting to prevent type inaccuracies without raising an exception or error).



                                                    If you'd like to keep the result as a double you're going to want to create a situation where you have
                                                    double var = double result



                                                    The easiest way to do that is to force the expression on the right side of an equation to cast to double:



                                                    c = a/(double)b



                                                    Division between an integer and a double will result in casting the integer to the double (note that when doing maths, the compiler will often "upcast" to the most specific data type this is to prevent data loss).



                                                    After the upcast, a will wind up as a double and now you have division between two doubles. This will create the desired division and assignment.



                                                    AGAIN, please note that this is language specific (and can even be compiler specific), however almost all languages (certainly all the ones I can think of off the top of my head) treat this example identically.






                                                    share|improve this answer

























                                                    • This question is tagged [C++], and the C++ Standard dictates exactly how this works. Not sure what you mean by "language specific" and it's certainly not compiler-specific, assuming no compiler extenstions are engaged.

                                                      – John Dibling
                                                      Sep 27 '11 at 15:32












                                                    • Also it's incorrect to say that "double var = integer result which casts the double var down to int". The double isn't cast to an int. The int result is converted to a double.

                                                      – John Dibling
                                                      Sep 27 '11 at 15:35











                                                    • I was allowing for the possibility of compiler extensions (I've actually had this issue once where my environment was "mis-casting" the results and I couldn't figure out why). And the result is language specific as in some languages don't follow the same casting rules. I didn't consider that it was a C++ specific tag. You're right about the "double var = integer result" comment. Edited to reflect that. Thank you!

                                                      – matthewdunnam
                                                      Sep 27 '11 at 20:18
















                                                    2














                                                    This is technically a language-dependent, but almost all languages treat this subject the same. When there is a type mismatch between two data types in an expression, most languages will try to cast the data on one side of the = to match the data on the other side according to a set of predefined rules.



                                                    When dividing two numbers of the same type (integers, doubles, etc.) the result will always be of the same type (so 'int/int' will always result in int).



                                                    In this case you have
                                                    double var = integer result
                                                    which casts the integer result to a double after the calculation in which case the fractional data is already lost. (most languages will do this casting to prevent type inaccuracies without raising an exception or error).



                                                    If you'd like to keep the result as a double you're going to want to create a situation where you have
                                                    double var = double result



                                                    The easiest way to do that is to force the expression on the right side of an equation to cast to double:



                                                    c = a/(double)b



                                                    Division between an integer and a double will result in casting the integer to the double (note that when doing maths, the compiler will often "upcast" to the most specific data type this is to prevent data loss).



                                                    After the upcast, a will wind up as a double and now you have division between two doubles. This will create the desired division and assignment.



                                                    AGAIN, please note that this is language specific (and can even be compiler specific), however almost all languages (certainly all the ones I can think of off the top of my head) treat this example identically.






                                                    share|improve this answer

























                                                    • This question is tagged [C++], and the C++ Standard dictates exactly how this works. Not sure what you mean by "language specific" and it's certainly not compiler-specific, assuming no compiler extenstions are engaged.

                                                      – John Dibling
                                                      Sep 27 '11 at 15:32












                                                    • Also it's incorrect to say that "double var = integer result which casts the double var down to int". The double isn't cast to an int. The int result is converted to a double.

                                                      – John Dibling
                                                      Sep 27 '11 at 15:35











                                                    • I was allowing for the possibility of compiler extensions (I've actually had this issue once where my environment was "mis-casting" the results and I couldn't figure out why). And the result is language specific as in some languages don't follow the same casting rules. I didn't consider that it was a C++ specific tag. You're right about the "double var = integer result" comment. Edited to reflect that. Thank you!

                                                      – matthewdunnam
                                                      Sep 27 '11 at 20:18














                                                    2












                                                    2








                                                    2







                                                    This is technically a language-dependent, but almost all languages treat this subject the same. When there is a type mismatch between two data types in an expression, most languages will try to cast the data on one side of the = to match the data on the other side according to a set of predefined rules.



                                                    When dividing two numbers of the same type (integers, doubles, etc.) the result will always be of the same type (so 'int/int' will always result in int).



                                                    In this case you have
                                                    double var = integer result
                                                    which casts the integer result to a double after the calculation in which case the fractional data is already lost. (most languages will do this casting to prevent type inaccuracies without raising an exception or error).



                                                    If you'd like to keep the result as a double you're going to want to create a situation where you have
                                                    double var = double result



                                                    The easiest way to do that is to force the expression on the right side of an equation to cast to double:



                                                    c = a/(double)b



                                                    Division between an integer and a double will result in casting the integer to the double (note that when doing maths, the compiler will often "upcast" to the most specific data type this is to prevent data loss).



                                                    After the upcast, a will wind up as a double and now you have division between two doubles. This will create the desired division and assignment.



                                                    AGAIN, please note that this is language specific (and can even be compiler specific), however almost all languages (certainly all the ones I can think of off the top of my head) treat this example identically.






                                                    share|improve this answer















                                                    This is technically a language-dependent, but almost all languages treat this subject the same. When there is a type mismatch between two data types in an expression, most languages will try to cast the data on one side of the = to match the data on the other side according to a set of predefined rules.



                                                    When dividing two numbers of the same type (integers, doubles, etc.) the result will always be of the same type (so 'int/int' will always result in int).



                                                    In this case you have
                                                    double var = integer result
                                                    which casts the integer result to a double after the calculation in which case the fractional data is already lost. (most languages will do this casting to prevent type inaccuracies without raising an exception or error).



                                                    If you'd like to keep the result as a double you're going to want to create a situation where you have
                                                    double var = double result



                                                    The easiest way to do that is to force the expression on the right side of an equation to cast to double:



                                                    c = a/(double)b



                                                    Division between an integer and a double will result in casting the integer to the double (note that when doing maths, the compiler will often "upcast" to the most specific data type this is to prevent data loss).



                                                    After the upcast, a will wind up as a double and now you have division between two doubles. This will create the desired division and assignment.



                                                    AGAIN, please note that this is language specific (and can even be compiler specific), however almost all languages (certainly all the ones I can think of off the top of my head) treat this example identically.







                                                    share|improve this answer














                                                    share|improve this answer



                                                    share|improve this answer








                                                    edited Sep 27 '11 at 20:22

























                                                    answered Sep 27 '11 at 15:12









                                                    matthewdunnammatthewdunnam

                                                    9862 gold badges15 silver badges32 bronze badges




                                                    9862 gold badges15 silver badges32 bronze badges












                                                    • This question is tagged [C++], and the C++ Standard dictates exactly how this works. Not sure what you mean by "language specific" and it's certainly not compiler-specific, assuming no compiler extenstions are engaged.

                                                      – John Dibling
                                                      Sep 27 '11 at 15:32












                                                    • Also it's incorrect to say that "double var = integer result which casts the double var down to int". The double isn't cast to an int. The int result is converted to a double.

                                                      – John Dibling
                                                      Sep 27 '11 at 15:35











                                                    • I was allowing for the possibility of compiler extensions (I've actually had this issue once where my environment was "mis-casting" the results and I couldn't figure out why). And the result is language specific as in some languages don't follow the same casting rules. I didn't consider that it was a C++ specific tag. You're right about the "double var = integer result" comment. Edited to reflect that. Thank you!

                                                      – matthewdunnam
                                                      Sep 27 '11 at 20:18


















                                                    • This question is tagged [C++], and the C++ Standard dictates exactly how this works. Not sure what you mean by "language specific" and it's certainly not compiler-specific, assuming no compiler extenstions are engaged.

                                                      – John Dibling
                                                      Sep 27 '11 at 15:32












                                                    • Also it's incorrect to say that "double var = integer result which casts the double var down to int". The double isn't cast to an int. The int result is converted to a double.

                                                      – John Dibling
                                                      Sep 27 '11 at 15:35











                                                    • I was allowing for the possibility of compiler extensions (I've actually had this issue once where my environment was "mis-casting" the results and I couldn't figure out why). And the result is language specific as in some languages don't follow the same casting rules. I didn't consider that it was a C++ specific tag. You're right about the "double var = integer result" comment. Edited to reflect that. Thank you!

                                                      – matthewdunnam
                                                      Sep 27 '11 at 20:18

















                                                    This question is tagged [C++], and the C++ Standard dictates exactly how this works. Not sure what you mean by "language specific" and it's certainly not compiler-specific, assuming no compiler extenstions are engaged.

                                                    – John Dibling
                                                    Sep 27 '11 at 15:32






                                                    This question is tagged [C++], and the C++ Standard dictates exactly how this works. Not sure what you mean by "language specific" and it's certainly not compiler-specific, assuming no compiler extenstions are engaged.

                                                    – John Dibling
                                                    Sep 27 '11 at 15:32














                                                    Also it's incorrect to say that "double var = integer result which casts the double var down to int". The double isn't cast to an int. The int result is converted to a double.

                                                    – John Dibling
                                                    Sep 27 '11 at 15:35





                                                    Also it's incorrect to say that "double var = integer result which casts the double var down to int". The double isn't cast to an int. The int result is converted to a double.

                                                    – John Dibling
                                                    Sep 27 '11 at 15:35













                                                    I was allowing for the possibility of compiler extensions (I've actually had this issue once where my environment was "mis-casting" the results and I couldn't figure out why). And the result is language specific as in some languages don't follow the same casting rules. I didn't consider that it was a C++ specific tag. You're right about the "double var = integer result" comment. Edited to reflect that. Thank you!

                                                    – matthewdunnam
                                                    Sep 27 '11 at 20:18






                                                    I was allowing for the possibility of compiler extensions (I've actually had this issue once where my environment was "mis-casting" the results and I couldn't figure out why). And the result is language specific as in some languages don't follow the same casting rules. I didn't consider that it was a C++ specific tag. You're right about the "double var = integer result" comment. Edited to reflect that. Thank you!

                                                    – matthewdunnam
                                                    Sep 27 '11 at 20:18


















                                                    draft saved

                                                    draft discarded
















































                                                    Thanks for contributing an answer to Stack Overflow!


                                                    • Please be sure to answer the question. Provide details and share your research!

                                                    But avoid


                                                    • Asking for help, clarification, or responding to other answers.

                                                    • Making statements based on opinion; back them up with references or personal experience.

                                                    To learn more, see our tips on writing great answers.




                                                    draft saved


                                                    draft discarded














                                                    StackExchange.ready(
                                                    function ()
                                                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f7571326%2fwhy-does-dividing-two-int-not-yield-the-right-value-when-assigned-to-double%23new-answer', 'question_page');

                                                    );

                                                    Post as a guest















                                                    Required, but never shown





















































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown

































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown







                                                    Popular posts from this blog

                                                    Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                                                    SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                                                    은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현