Thread: float type- beginner Q

  1. #1
    Registered User
    Join Date
    Jan 2011
    Posts
    222

    float type- beginner Q

    hi,

    what is wrong with this code :

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(){
    int a =1;
    int b = 2;
    int c = 0;
    float i = 0;
    
    c= a-b;
    i = a/b;
    printf("%d,%f\n",c,i);
    }
    I am expecting to print 2 numbers : -1 and 0.5, but i get -1 and 0.000000. What am i doing wrong

    thank you

    baxy

  2. #2
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    Code:
    i = (float)a/(float)b;
    What happens is that the division kills your precision

  3. #3
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,835
    When you do a/b where both 'a' and 'b' are ints, the compiler uses integer arithmetic and returns an int result. If you want to ensure the division is done using floating point, force one of the numbers to be float: i = (float)a / b

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Float Data Type Ranges
    By GokhanK in forum C Programming
    Replies: 1
    Last Post: 02-26-2011, 02:17 PM
  2. Float data type issue
    By Figen in forum C Programming
    Replies: 2
    Last Post: 01-31-2011, 12:42 PM
  3. [beginner] float and division
    By codezero in forum C Programming
    Replies: 5
    Last Post: 04-27-2009, 09:32 PM
  4. Please help a beginner with float...
    By BobDole11 in forum C Programming
    Replies: 4
    Last Post: 09-14-2008, 11:06 AM
  5. Beginner's C, problems with double, float
    By wileyokiley in forum C Programming
    Replies: 4
    Last Post: 08-17-2007, 08:06 AM