Thread: Problem with the Result of the code

  1. #1
    Registered User
    Join Date
    Nov 2018
    Posts
    1

    Problem with the Result of the code

    Code:
    #include <stdio.h>
    #include <math.h>
    int main()
    {
        int i, k;
        for(i = 0; i < 6; i++){
            k = pow(10, i);
            printf("%d\t", k);
        }
        return 0;
    }
    Getting this result
    Code:
    1     10     99    1000    9999    100000
    But i want
    Code:
    1     10     100    1000    10000    100000
    where is my bug??

  2. #2
    Registered User
    Join Date
    Dec 2017
    Posts
    862
    pow returns a floating point value which will not be exact. In converting it to an integer, the decimals are just thrown away, even if they are .99999
    So you probably want to round up the result by adding 0.5.
    Code:
    k = int(pow(10, i) + 0.5);  // added .5 to round up (and made cast to int explicit so it's more obvious)
    If you really just want powers of 10, pow may not be the best choice. It's probably better to start an integer at 1 and repeatedly multiply it by 10. But beware of going beyond the limit of the type.
    The world hangs on a thin thread, and that is the psyche of man. - Carl Jung

  3. #3
    Registered User
    Join Date
    Apr 2017
    Location
    Iran
    Posts
    100
    Consider this:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
        int i;
        int k=1;
        
        for(i=1; i<7; i++)
        {
            printf("%d\n",k);
            k *= 10;
        }
    
        return EXIT_SUCCESS;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 09-24-2013, 10:33 AM
  2. Problem with print out the result
    By pp00 in forum C Programming
    Replies: 11
    Last Post: 11-14-2012, 01:56 AM
  3. Weird result with code
    By raesoo80 in forum Tech Board
    Replies: 8
    Last Post: 12-14-2010, 02:30 PM
  4. Replies: 4
    Last Post: 04-24-2004, 04:29 PM
  5. same code, different result?!
    By Hunter2 in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2002, 10:01 PM

Tags for this Thread