why are all of them 0

This is a discussion on why are all of them 0 within the C Programming forums, part of the General Programming Boards category; Code: void printFloat() { printf("%f\n",2/3); } int main() { printFloat(); float a = 2/3; printf("%f\n",a); return 0; }...

  1. #1
    Registered User
    Join Date
    Aug 2009
    Posts
    168

    why are all of them 0

    Code:
    void printFloat()
    {
         printf("%f\n",2/3);
    }
    int main()
    {
        printFloat();
        float a = 2/3;
        printf("%f\n",a);
        return 0;
    }

  2. #2
    Registered User
    Join Date
    Aug 2009
    Posts
    168
    I know:
    because 2 and 3 is int type.

  3. #3
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,832
    Yup. You can force it to do the calculation in floating point:
    Code:
    2.0/3
    Now because one of the numbers is floating point, the calculation is done that way and the result will be float as well.

  4. #4
    Third Eye Babkockdood's Avatar
    Join Date
    Apr 2010
    Posts
    352
    2/3 (assuming that's two divided by three) is an integer. Try this.

    Code:
    void printFloat()
    {
         printf("%d\n",2/3);
    }
    int main()
    {
        printFloat();
        int a = 2/3;
        printf("%d\n",a);
        return 0;
    }
    Output:
    Code:
    0
    0
    It gives you two zeros because the program sees anything less than one is zero. I think there's a function that gives you the actual decimal, but if you were to get the actual decimal of two divided by three, the screen would flood with sixes.
    Last edited by Babkockdood; 04-29-2010 at 08:43 PM.

  5. #5
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Code:
    void printFloat()
    {
         printf("%d\n",2/3);
    }
    printFloat doesn't actually print a float. You're still using %d, and, you're still using integers.


    Quzah.
    Hope is the first step on the road to disappointment.

  6. #6
    Third Eye Babkockdood's Avatar
    Join Date
    Apr 2010
    Posts
    352
    Quote Originally Posted by quzah View Post
    Code:
    void printFloat()
    {
         printf("%d\n",2/3);
    }
    printFloat doesn't actually print a float. You're still using %d, and, you're still using integers.


    Quzah.
    Well zcrself named the function :P

Popular pages Recent additions subscribe to a feed

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