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;
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
add a comment |
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
Possible duplicate of Division result is always zero
– phuclv
Sep 9 '18 at 4:51
add a comment |
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
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
c++ variables double integer-division
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
add a comment |
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
add a comment |
8 Answers
8
active
oldest
votes
This is because you are using the integer division version of operator/
, which takes 2 int
s and returns an int
. In order to use the double
version, which returns a double
, at least one of the int
s must be explicitly casted to a double
.
c = a/(double)b;
9
I would prefer to explicitly convert botha
andb
todouble
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 gettingstatic_cast<>
andreinterpret_cast<>
mixed up.
– Chad La Guardia
Sep 27 '11 at 15:47
6
@Tux-D: For arithmetic casts? I would prefer to avoidstatic_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 writingdouble(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
|
show 2 more comments
Here it is:
a) Dividing two int
s 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 int
s, 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.
add a comment |
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
.
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
add a comment |
When you divide two integers, the result will be an integer, irrespective of the fact that you store it in a double.
add a comment |
c
is a double
variable, but the value being assigned to it is an int
value because it results from the division of two int
s, which gives you "integer division" (dropping the remainder). So what happens in the line c=a/b
is
a/b
is evaluated, creating a temporary of typeint
- the value of the temporary is assigned to
c
after conversion to typedouble
.
The value of a/b
is determined without reference to its context (assignment to double
).
add a comment |
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.
add a comment |
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.
add a comment |
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 havedouble 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 havedouble 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.
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
add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
This is because you are using the integer division version of operator/
, which takes 2 int
s and returns an int
. In order to use the double
version, which returns a double
, at least one of the int
s must be explicitly casted to a double
.
c = a/(double)b;
9
I would prefer to explicitly convert botha
andb
todouble
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 gettingstatic_cast<>
andreinterpret_cast<>
mixed up.
– Chad La Guardia
Sep 27 '11 at 15:47
6
@Tux-D: For arithmetic casts? I would prefer to avoidstatic_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 writingdouble(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
|
show 2 more comments
This is because you are using the integer division version of operator/
, which takes 2 int
s and returns an int
. In order to use the double
version, which returns a double
, at least one of the int
s must be explicitly casted to a double
.
c = a/(double)b;
9
I would prefer to explicitly convert botha
andb
todouble
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 gettingstatic_cast<>
andreinterpret_cast<>
mixed up.
– Chad La Guardia
Sep 27 '11 at 15:47
6
@Tux-D: For arithmetic casts? I would prefer to avoidstatic_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 writingdouble(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
|
show 2 more comments
This is because you are using the integer division version of operator/
, which takes 2 int
s and returns an int
. In order to use the double
version, which returns a double
, at least one of the int
s must be explicitly casted to a double
.
c = a/(double)b;
This is because you are using the integer division version of operator/
, which takes 2 int
s and returns an int
. In order to use the double
version, which returns a double
, at least one of the int
s must be explicitly casted to a double
.
c = a/(double)b;
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 botha
andb
todouble
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 gettingstatic_cast<>
andreinterpret_cast<>
mixed up.
– Chad La Guardia
Sep 27 '11 at 15:47
6
@Tux-D: For arithmetic casts? I would prefer to avoidstatic_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 writingdouble(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
|
show 2 more comments
9
I would prefer to explicitly convert botha
andb
todouble
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 gettingstatic_cast<>
andreinterpret_cast<>
mixed up.
– Chad La Guardia
Sep 27 '11 at 15:47
6
@Tux-D: For arithmetic casts? I would prefer to avoidstatic_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 writingdouble(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
|
show 2 more comments
Here it is:
a) Dividing two int
s 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 int
s, 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.
add a comment |
Here it is:
a) Dividing two int
s 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 int
s, 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.
add a comment |
Here it is:
a) Dividing two int
s 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 int
s, 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.
Here it is:
a) Dividing two int
s 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 int
s, 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.
answered Sep 27 '11 at 15:15
nplatisnplatis
3671 silver badge8 bronze badges
3671 silver badge8 bronze badges
add a comment |
add a comment |
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
.
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
add a comment |
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
.
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
add a comment |
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
.
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
.
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
add a comment |
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
add a comment |
When you divide two integers, the result will be an integer, irrespective of the fact that you store it in a double.
add a comment |
When you divide two integers, the result will be an integer, irrespective of the fact that you store it in a double.
add a comment |
When you divide two integers, the result will be an integer, irrespective of the fact that you store it in a double.
When you divide two integers, the result will be an integer, irrespective of the fact that you store it in a double.
answered Sep 27 '11 at 15:06
Alok SaveAlok Save
168k37 gold badges358 silver badges491 bronze badges
168k37 gold badges358 silver badges491 bronze badges
add a comment |
add a comment |
c
is a double
variable, but the value being assigned to it is an int
value because it results from the division of two int
s, which gives you "integer division" (dropping the remainder). So what happens in the line c=a/b
is
a/b
is evaluated, creating a temporary of typeint
- the value of the temporary is assigned to
c
after conversion to typedouble
.
The value of a/b
is determined without reference to its context (assignment to double
).
add a comment |
c
is a double
variable, but the value being assigned to it is an int
value because it results from the division of two int
s, which gives you "integer division" (dropping the remainder). So what happens in the line c=a/b
is
a/b
is evaluated, creating a temporary of typeint
- the value of the temporary is assigned to
c
after conversion to typedouble
.
The value of a/b
is determined without reference to its context (assignment to double
).
add a comment |
c
is a double
variable, but the value being assigned to it is an int
value because it results from the division of two int
s, which gives you "integer division" (dropping the remainder). So what happens in the line c=a/b
is
a/b
is evaluated, creating a temporary of typeint
- the value of the temporary is assigned to
c
after conversion to typedouble
.
The value of a/b
is determined without reference to its context (assignment to double
).
c
is a double
variable, but the value being assigned to it is an int
value because it results from the division of two int
s, which gives you "integer division" (dropping the remainder). So what happens in the line c=a/b
is
a/b
is evaluated, creating a temporary of typeint
- the value of the temporary is assigned to
c
after conversion to typedouble
.
The value of a/b
is determined without reference to its context (assignment to double
).
answered Sep 27 '11 at 15:04
Fred FooFred Foo
288k59 gold badges611 silver badges741 bronze badges
288k59 gold badges611 silver badges741 bronze badges
add a comment |
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
answered Sep 27 '11 at 15:07
VickyVicky
10.9k2 gold badges41 silver badges49 bronze badges
10.9k2 gold badges41 silver badges49 bronze badges
add a comment |
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
answered Sep 27 '11 at 16:20
AnTAnT
265k35 gold badges431 silver badges674 bronze badges
265k35 gold badges431 silver badges674 bronze badges
add a comment |
add a comment |
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 havedouble 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 havedouble 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.
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
add a comment |
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 havedouble 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 havedouble 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.
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
add a comment |
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 havedouble 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 havedouble 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.
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 havedouble 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 havedouble 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.
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
add a comment |
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
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
Possible duplicate of Division result is always zero
– phuclv
Sep 9 '18 at 4:51