Thread: Cannot divide

  1. #1
    Registered User
    Join Date
    May 2003
    Posts
    2

    Cannot divide

    Hello,

    I have two variables, x and y, inside a loop. X gets the value of an AP (1,3,5,7,...) while Y gets the value of a GP (1,-1,1,-1). My problem is that the value of 1(x*y) is rounded by the computer to 0. Here is part of the source code of my program.

    ...
    float value;
    ...
    while (loop_count != max){
    ...
    value += 1/(x*y);
    ...

    What am I doing wrong? How can I fix this?

    Thanks a lot!

  2. #2
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    It may be a problem with the integer division. For starters, you can see if value += 1.0/(x*y) fixes this. Integer division of 1 by some large number will get truncated to 0 and then assigned to value.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  3. #3
    Registered User axon's Avatar
    Join Date
    Feb 2003
    Posts
    2,572
    ...also look what type is your 'x' and 'y' variable, and how they are initialized.
    Code:
    double x = 4.0; //something like that
    axon

    some entropy with that sink? entropysink.com

    there are two cardinal sins from which all others spring: Impatience and Laziness. - franz kafka

  4. #4
    Registered User
    Join Date
    May 2003
    Posts
    2
    Originally posted by hk_mp5kpdw
    It may be a problem with the integer division. For starters, you can see if value += 1.0/(x*y) fixes this. Integer division of 1 by some large number will get truncated to 0 and then assigned to value.
    Thank you, it worked out.
    I've got another question:

    The program I'm creating calculates pi with Leibniz procedure [4*(1/1 - 1/3 + 1/5 - 1/7 + ...)]. The problem is that it only gives precision of 4 characters (3,1415). How can I increase this?

    Thanks!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. divide by zero
    By George2 in forum C# Programming
    Replies: 17
    Last Post: 05-02-2008, 02:37 AM
  2. Divide 64bit number
    By freeindy in forum C Programming
    Replies: 4
    Last Post: 10-01-2007, 03:56 AM
  3. Divide and Conquer: array in the reverse order
    By Steamer in forum C Programming
    Replies: 11
    Last Post: 03-08-2004, 07:31 PM
  4. severe beating of divide by zero
    By muttski in forum A Brief History of Cprogramming.com
    Replies: 6
    Last Post: 11-22-2002, 05:54 PM
  5. Divide and Average Algorithm
    By Unregistered in forum C Programming
    Replies: 1
    Last Post: 01-25-2002, 03:30 PM