# Thread: Casting problem

1. ## Casting problem

I have a problem with casting.

I have a class Complex, where a Complex object is a complex number. The real and complex parts are floats. I sum several complex numbers, and I know that this sum is always an integer. I want to convert it to a long. The problem is that even though the sum is 11 , when I cast it to a long the result it 10. Why?

Code:
```class Complex{
float r, c; //r is the real part, c the complex; r + ci

public:

Complex(){
r = 0;
c = 0;
}

Complex(float real, float comp){
r = real;
c = comp;
}

float getReal(){
return r;
}

float getComp(){
return c;
}

}

long findKm(){
Comlex sum = //sum of several complex numbers that sums to a real number, which is an integer
long Km = static_cast<long>(sum.getReal())
return Km
}```

2. Because casting to an integer is truncation, not nearest.

So your calculation might be 11 on paper, but computationally, it's 10.999999999999
Casting it will make it 10, not 11.

Popular pages Recent additions