Double in object method not accepting fractional values?
I am having trouble with a C++ object-orientated script. When I create an object, I wish to calculate an AttributeQ
based on its attributes MyAValue
, MyBValue
, and MyCValue
.
While using the Visual 2010 debugger, I noticed that TempAttribueQ
seems to always be 0
(except before it is initialized of course). Assuming Delta != 0
, BVal == Maximum
, and DeltaA == DeltaC
, then TempAttribueQ
should be 1/3
not 0
.
At first I thought it was a scope problem, but the variable is defined outside the if-else
statements. I have tried initializing TempAttribueQ
as some outrageous number, which it keeps up until the if-else
statements when it becomes 0
when it shouldn't.
This is my code...
void SetMyAttribueQ(){
double TempAVal = MyAValue;
double TempBVal = MyBValue;
double TempCVal = MyCValue;
double Minimum = min(min(TempAVal, TempBVal), TempCVal);
double Maximum = max(max(TempAVal, TempBVal), TempCVal);
double Delta = Maximum - Minimum;
double DeltaA = 0;
double DeltaB = 0;
double DeltaC = 0;
double TempAttribueQ = 0;
if(Delta == 0) {
MyAttribueQ = TempAttribueQ; // this->SetMyAttribueQ(TempAttribueQ);
}
else {
DeltaA = /* (a removed equation goes here... */
DeltaB = /* (a removed equation goes here... */
DeltaC = /* (a removed equatio开发者_运维知识库n goes here... */
if(AVal == Maximum)
TempAttribueQ = (DeltaC - DeltaB);
else if(BVal == Maximum)
TempAttribueQ = (1/3) + (DeltaA - DeltaC);
else
TempAttribueQ = (2/3) + (DeltaB - DeltaA);
MyAttribueQ = TempAttribueQ;
}
}
What is preventing TempAttribueQ
from getting a value of 1/3
or 2/3
? Or, what is causing it to be set to be set to 0
?
When you divide one integer by another, you get an integer result. Change either or both the constants to non-integer to fix it - C++ rules will result in the other being converted to floating point before the division takes place. All of the following will work:
- 1.0 / 3.0
- 1 / 3.0
- 1.0 / 3
An integer will get converted back to a double invisibly, which is why you weren't seeing any errors in your code.
1
is an integer and 3
is an integer so 1/3
uses integer arithmetic.
You want to use 1.0/3.0
to force double precision arithmetic.
1/3 == 0
due to integer division, which is set to TempAttribueQ
.
You need to do 1./3
which will produce 0.3333333..
Try 1.0/3.0 and 2.0/3.0. 1/3 and 2/3 are 0 due to integer division.
精彩评论