Thread: Casting problem

  1. #1
    Registered User
    Join Date
    May 2007

    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?

    class Complex{
    	float r, c; //r is the real part, c the complex; r + ci
                r = 0;
                c = 0;
    	Complex(float real, float comp){
    	r = real;
    	c = comp;
    	float getReal(){
    		return r;
    	float getComp(){
    		return c;
            //additional irrelevant functions
    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
    Last edited by Wilhelmina; 07-19-2007 at 07:58 AM.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    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.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Laptop Problem
    By Boomba in forum Tech Board
    Replies: 1
    Last Post: 03-07-2006, 06:24 PM
  2. type casting problem?
    By lackofcolour in forum C Programming
    Replies: 6
    Last Post: 01-30-2006, 04:29 PM
  3. Replies: 5
    Last Post: 11-07-2005, 11:34 PM
  4. half ADT (nested struct) problem...
    By CyC|OpS in forum C Programming
    Replies: 1
    Last Post: 10-26-2002, 08:37 AM
  5. binary tree problem - help needed
    By sanju in forum C Programming
    Replies: 4
    Last Post: 10-16-2002, 05:18 AM