Thread: Problem in printing float

  1. #1
    Registered User
    Join Date
    Feb 2016
    Posts
    3

    Problem in printing float

    Hi,
    I am a beginner in C programming, and when trying to see how the type "float" works, I typed in
    Code:
    #include <stdio.h>
    
    
    
    int main(int argc, const char * argv[]) {
    // insert code here...
        int a;
        float b;
    
        a = getchar();
        b = a/100;
    
        printf("%1.3f\n",b);
    
    }
    but the results, whatever it should be, would only give me 0.000

    And I get weird numbers too here,
    Code:
    int main(int argc, constchar * argv[]) {// insert code here...
        float b;
        b = getchar();
        printf("%1.3f\n",b);
    }
    It would be great if you could teach me why it gives me these totally wrong answers and how to fix it.

    Thanks a lot!

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    I don't know what floats you are expecting to get from getchar(). In general that method is very inadequate. You should be at least asking for a string that you convert to a floating point number. You could also use scanf() I suppose.

    Consider this:
    Code:
    #include <stdio.h>
    int main(int argc, char **argv) {
       double b;
       if (scanf("%f", &b) == 1) {
          printf("%1.3f\n", b);
       }
       return 0;
    }

  3. #3
    Registered User
    Join Date
    Dec 2015
    Posts
    112
    You can try that example with double and float and change the precision in the print statement to see how it affects the displayed value.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem with printing float precision values.
    By vebi1000 in forum C Programming
    Replies: 1
    Last Post: 11-22-2012, 03:36 PM
  2. Printing float number in MessageBox with Unicode
    By mvanrijnbach in forum Windows Programming
    Replies: 10
    Last Post: 02-18-2010, 01:25 AM
  3. Printing a float's bytes...
    By Mr_Miguel in forum C Programming
    Replies: 3
    Last Post: 01-07-2008, 09:06 AM
  4. Printf float printing
    By judgex in forum C Programming
    Replies: 3
    Last Post: 12-08-2007, 02:47 AM
  5. Printing float numbers
    By gustavosserra in forum C++ Programming
    Replies: 4
    Last Post: 10-17-2003, 08:14 AM

Tags for this Thread