fractions

This is a discussion on fractions within the C Programming forums, part of the General Programming Boards category; Just a question about entering fractions... I have a function set up to do a simple calculation. If I code ...

  1. #1
    Registered User
    Join Date
    May 2008
    Posts
    30

    fractions

    Just a question about entering fractions...
    I have a function set up to do a simple calculation. If I code in a whole number to be multiplied by one of the variables, it gives the right answer but if it's a fraction - ie (1/2)*x - it gives the wrong answer. The answer it gives is as if the fraction were a 0 instead. It's also wrong for fractions greater than 0 that don't reduce to a whole number, except that the answer is like the x were multiplied by the fraction rounded to a whole number.
    Everything's okay if I put in the decimal instead, but I was just wondering if there's a special way to enter fractions?

  2. #2
    Woof, woof! zacs7's Avatar
    Join Date
    Mar 2007
    Location
    Australia
    Posts
    3,459
    (1/2) = 0.5 (however, since it's an integer division it's truncated to 0).

    (1.0f / 2.0f) * (float) x
    Is perhaps a better way.

    int / int gives an int
    float / float gives a float
    double / double gives a double

    So on and so forth.

  3. #3
    Registered User
    Join Date
    May 2008
    Posts
    30
    Oh, awesome! Thanks, I just needed to put the .0 in...should have tried that. I'm new at this... :P

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Algebraic Fractions
    By treenef in forum C++ Programming
    Replies: 8
    Last Post: 12-20-2005, 05:10 AM
  2. Need help woth fractions..
    By snapshooter in forum C Programming
    Replies: 4
    Last Post: 11-17-2004, 06:51 PM
  3. Greatest Common Factors of Fractions
    By sonict in forum C++ Programming
    Replies: 1
    Last Post: 01-15-2003, 04:33 AM
  4. Fractions
    By Unregistered in forum C++ Programming
    Replies: 2
    Last Post: 04-01-2002, 07:51 AM
  5. Decimals to Fractions
    By ToasterPas in forum C++ Programming
    Replies: 4
    Last Post: 12-28-2001, 12:58 PM

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