simple calculation of division

This is a discussion on simple calculation of division within the C Programming forums, part of the General Programming Boards category; Hello, I am writing a simple C program using Visual studio 2008. And when I divide 5 / 9. I ...

  1. #1
    UK2
    Join Date
    Sep 2003
    Posts
    112

    simple calculation of division

    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;
    }

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    Because 5/9 is 0 (remainder 5, but you didn't ask for that). Now, 5.0/9.0 is 0.555555, or as near as the computer can get to that number in 32 bits.

  3. #3
    ... kermit's Avatar
    Join Date
    Jan 2003
    Posts
    1,528
    Why do you return an int from your function, when you are attempting to generate a float or double? Even if you fix your division, as tabstop indicated, your calling function will never see that float.
    Last edited by kermit; 09-13-2008 at 05:41 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need help with basic calculation program.
    By StateofMind in forum C Programming
    Replies: 18
    Last Post: 03-06-2009, 12:44 AM
  2. Binary division of large numbers
    By hooper in forum C Programming
    Replies: 5
    Last Post: 06-01-2007, 02:33 AM
  3. Problem with modus division.
    By stillwell in forum C++ Programming
    Replies: 3
    Last Post: 10-19-2004, 11:54 AM
  4. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  5. Simple calculation not working, need help
    By Summonerur in forum C Programming
    Replies: 20
    Last Post: 09-24-2004, 02:53 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21