Thread: floating point error

  1. #1
    Unregistered
    Guest

    Question floating point error

    hi!
    got some problems with inversing numbers. Everytime i compile and run, the floating point variable (inverse) gives a zero. Tried using different compilers and they give the same result. Any ideas?

    unsigned int k, x, factorial_x=1, sum=0;
    float inverse;



    for(k=5; k>=1; k--){
    for(x=k; x>=1; x--)
    factorial_x *= x;
    inverse= 1/factorial_x;
    factorial_x = 1;
    printf("%f", inverse);
    }

  2. #2
    S­énior Member
    Join Date
    Jan 2002
    Posts
    982
    If you divide one integer by another, you'll get an integer as the result, regardless of the type of variable you're storing it in. Try -

    inverse= 1./factorial_x;

  3. #3
    Code Warrior
    Join Date
    Nov 2001
    Posts
    669
    Try this:

    Code:
    # include <stdio.h>
    # include <conio.h>
    
    int main()
    {
       int k, x;
       float inverse, factorial_x=1;
    
       clrscr();
       for(k=5; k>=1; k--)
       {
          for(x=k; x>=1; x--)
          {
             factorial_x *= x;
             inverse      = 1 / factorial_x;
          }
          factorial_x = 1;
          printf("%f\n", inverse);
       }
       getch();
       return 0;
    }
    That's All!
    Current projects:
    1) User Interface Development Kit (C++)
    2) HTML SDK (C++)
    3) Classes (C++)
    4) INI Editor (Delphi)

  4. #4
    Unregistered
    Guest
    just change a bit instead of chaanging whole program
    changed code is here:


    unsigned int k, x, factorial_x=1, sum=0;
    float inverse;



    for(k=5; k>=1; k--){
    for(x=k; x>=1; x--)
    factorial_x *= x;
    inverse= (float)1/(float)factorial_x;
    factorial_x = 1;
    printf("%f", inverse);
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Quantum Random Bit Generator
    By shawnt in forum C++ Programming
    Replies: 62
    Last Post: 06-18-2008, 10:17 AM
  2. Crazy errors caused by class, never seen before..
    By Shamino in forum C++ Programming
    Replies: 2
    Last Post: 06-10-2007, 11:54 AM
  3. Connecting to a mysql server and querying problem
    By Diod in forum C++ Programming
    Replies: 8
    Last Post: 02-13-2006, 10:33 AM
  4. Game Pointer Trouble?
    By Drahcir in forum C Programming
    Replies: 8
    Last Post: 02-04-2006, 02:53 AM
  5. Problem with Visual C++ Object-Oriented Programming Book.
    By GameGenie in forum C++ Programming
    Replies: 9
    Last Post: 08-29-2005, 11:21 PM