Results 1 to 2 of 2

Thread: [RESOLVED] float valueA = 5/9; Always evaulates to 0

  1. #1

    Thread Starter
    Frenzied Member
    Join Date
    Dec 2001
    Posts
    1,331

    Resolved [RESOLVED] float valueA = 5/9; Always evaulates to 0

    Hello,

    I am writing a simple C program using Visual studio 2008.

    And when I divide 5 / 9. I always get an zero. However, the correct value should be 0.5555.

    Can anyone explain this?

    Many thanks

    Code:
    //Calculate the temperature in celsius
    int CalculateCelsius(int fahrenheit)
    {
    	float valueA = 0;
    	int valueB = 0;
    	float celsius = 0;
    	
    	valueA = 5 / 9; //Always displays zero
    	valueB = fahrenheit - 32;
    	celsius = valueA * valueB;
    
    	return (int) celsius;
    }
    steve

  2. #2
    Smitten by reality Harsh Gupta's Avatar
    Join Date
    Feb 2005
    Posts
    2,938

    Re: float valueA = 5/9; Always evaulates to 0

    Since 5 and 9 are integers, the casting (or conversion) takes place after 5/9 is evaluated (which will be 0 in case of ints) and then converted to type float.

    Try by converting either numerator or denominator to type float and that should work.

    Code:
    //one of them should work
    
    valueA = 5f / 9; //or
    valueA = 5 / 9f; //or
    valueA = 5f / 9f;
    Show Appreciation. Rate Posts.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width