Thread: Strange Output

  1. #1
    Registered User
    Join Date
    Jan 2008

    Strange Output

    When i run this programme i get the following output:


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

           int val;
           val = 20;
           float num = 2.0/3.0;
           printf("%5.4f \n",num); 
           printf("%-5f \n",val);
           return 0;

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Farncombe, Surrey, England
    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
    printf("%-5f\n", (double)val);
    Or use a integer format (that's PROBABLY what you really wanted anyways):
    printf("%-5d\n", (double)val);
    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, 03:56 AM
  2. Binary Search - Strange Output
    By mike_g in forum C Programming
    Replies: 13
    Last Post: 06-16-2007, 02:55 PM
  3. Connecting input iterator to output iterator
    By QuestionC in forum C++ Programming
    Replies: 2
    Last Post: 04-10-2007, 02:18 AM
  4. Trying to store system(command) Output
    By punxworm in forum C++ Programming
    Replies: 5
    Last Post: 04-20-2005, 06:46 PM
  5. Really strange, unexpected values from allocated variables
    By Jaken Veina in forum Windows Programming
    Replies: 6
    Last Post: 04-16-2005, 05:40 PM