Thread: Displaying fractions simple problem

  1. #1
    Registered User
    Join Date
    Jan 2008

    Displaying fractions simple problem

    i'm just starting to learn C and i have a problem with displaying fractions.

    My code:

          float num = 2/3;
          printf("%f", num);
          return 0;
    When i run this, the ouput is:


    How do i get it to output .666666??
    Also, how would i get the output to display correct to 6 decimal places?

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    How do i get it to output .666666??
    By using floating point division instead of integer division.

    Also, how would i get the output to display correct to 6 decimal places?
    By using the format flags for printf(). For example:
    int main(void)
        float num = 2.0f / 3.0f;
        printf("&#37;.6f", num);
        return 0;
    Last edited by laserlight; 01-19-2008 at 02:33 AM.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Simple File I/O problem
    By Ignited in forum C++ Programming
    Replies: 3
    Last Post: 01-07-2006, 10:49 AM
  2. Fairly simple problem
    By fatdunky in forum C Programming
    Replies: 1
    Last Post: 11-14-2005, 11:34 PM
  3. Simple Variable Problem
    By Cthulhu in forum C++ Programming
    Replies: 2
    Last Post: 11-11-2005, 04:07 PM
  4. Problem with simple XOR program
    By spike_ in forum C++ Programming
    Replies: 8
    Last Post: 08-17-2005, 12:09 AM
  5. Request for comments
    By Prelude in forum A Brief History of
    Replies: 15
    Last Post: 01-02-2004, 10:33 AM