division issue

This is a discussion on division issue within the C Programming forums, part of the General Programming Boards category; to get accurate result either numerator or denominator or both must be floating type. why this statement doesn't give the ...

  1. #1
    Registered User
    Join Date
    Feb 2009
    Posts
    9

    division issue

    to get accurate result either numerator or denominator or both must be floating type.

    why this statement doesn't give the accurate result?
    Code:
                  float f;
                  f= 21/5;
                  printf("%f",f);
    the output is 4.000

    what happens if we make changes so?
    Code:
                  float f;
                  f= 21.0/5;
                  printf("%f",f);
    output 4.200

    please give me the reason

  2. #2
    Registered User
    Join Date
    Feb 2009
    Posts
    278
    because 21 and 5 are integers. 21/5 returns an integer (4) which is then cast to the float(4.000). 21.0/5 returns a float (4.2) because the result is of the highest type, in this case, float.

  3. #3
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    Integer division gives an integer answer.

  4. #4
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,614
    21.0 / 5 returns a double.
    21.0f / 5 returns a float.
    It's amazing how many people mix up floats and doubles.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. float calculation issue
    By George2 in forum C# Programming
    Replies: 1
    Last Post: 05-26-2008, 04:56 AM
  2. Get jiffies?
    By pgzh in forum Linux Programming
    Replies: 6
    Last Post: 03-17-2008, 10:30 AM
  3. type safe issue
    By George2 in forum C++ Programming
    Replies: 4
    Last Post: 02-12-2008, 08:32 PM
  4. Modular Division problem
    By Malek in forum C++ Programming
    Replies: 7
    Last Post: 05-24-2003, 06:08 PM
  5. my first issue of GDM
    By DavidP in forum A Brief History of Cprogramming.com
    Replies: 0
    Last Post: 09-12-2002, 04:02 PM

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