Whats wrong ??

This is a discussion on Whats wrong ?? within the C Programming forums, part of the General Programming Boards category; x = 2/4; printf("%f", x); Output: 0.00000 How can 2/4 result is 0.000 ?? How can i make the output ...

  1. #1
    Registered User
    Join Date
    Mar 2004
    Posts
    41

    Whats wrong ??

    x = 2/4;
    printf("%f", x);


    Output:
    0.00000

    How can 2/4 result is 0.000 ?? How can i make the output so that it is 0.5

  2. #2
    Registered User
    Join Date
    Apr 2004
    Posts
    38
    I'm assuming X is declared to be an integer, right? The result of 2/4 is 0.5, but as X is in integer, it will simply truncate the result. Instead of .5 you see 0. Simply change X to a float. Also, if you only want it to display 1 or 2 decimal points, make sure you print it by using %.2f, x

  3. #3
    Yes, my avatar is stolen anonytmouse's Avatar
    Join Date
    Dec 2002
    Posts
    2,544
    An integer divided by an integer gives an integer.
    Use:
    Code:
    x = (float) 2 / (float) 4;
    // OR
    x = 2.0 / 4.0;

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 9
    Last Post: 07-15-2004, 04:30 PM
  2. Debugging-Looking in the wrong places
    By JaWiB in forum A Brief History of Cprogramming.com
    Replies: 1
    Last Post: 11-03-2003, 10:50 PM
  3. Confused: What is wrong with void??
    By Machewy in forum C++ Programming
    Replies: 19
    Last Post: 04-15-2003, 01:40 PM
  4. God
    By datainjector in forum A Brief History of Cprogramming.com
    Replies: 746
    Last Post: 12-22-2002, 12:01 PM
  5. Whats wrong?
    By Unregistered in forum C Programming
    Replies: 6
    Last Post: 07-14-2002, 02:04 PM

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