Strange Output

This is a discussion on Strange Output within the C Programming forums, part of the General Programming Boards category; When i run this programme i get the following output: 0.6667 0.666667 How come the second printf statement does not ...

  1. #1
    Registered User
    Join Date
    Jan 2008
    Posts
    3

    Strange Output

    When i run this programme i get the following output:

    0.6667
    0.666667

    How come the second printf statement does not use the "val" value?

    insert
    Code:
    main(){
           int val;
           val = 20;
           float num = 2.0/3.0;
           printf("%5.4f \n",num); 
           printf("%-5f \n",val);
           getchar();
           return 0;
           }
    thanx

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Because it's not a floating point value.

    For some reason, the printf function assumes that floating point values are stored in floating point registers, and not taking the data you have in the argument list. Now, it would also not produce the right output if it took the "val" value - it would produce some quite strange output - since it would essentially take the value 20 as a floating point value, and that would NOT be a valid floating point value.


    Either cast your val to float/double, e.g
    Code:
    printf("%-5f\n", (double)val);
    Or use a integer format (that's PROBABLY what you really wanted anyways):
    Code:
    printf("%-5d\n", (double)val);
    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Output an array in a textbox
    By Diablo02 in forum C# Programming
    Replies: 5
    Last Post: 10-18-2007, 04:56 AM
  2. Binary Search - Strange Output
    By mike_g in forum C Programming
    Replies: 13
    Last Post: 06-16-2007, 03:55 PM
  3. Connecting input iterator to output iterator
    By QuestionC in forum C++ Programming
    Replies: 2
    Last Post: 04-10-2007, 03:18 AM
  4. Trying to store system(command) Output
    By punxworm in forum C++ Programming
    Replies: 5
    Last Post: 04-20-2005, 07:46 PM
  5. Really strange, unexpected values from allocated variables
    By Jaken Veina in forum Windows Programming
    Replies: 6
    Last Post: 04-16-2005, 06:40 PM

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