How to printf long long

前端 未结 4 984
南旧
南旧 2020-11-30 10:48

I\'m doing a program that aproximate PI and i\'m trying to use long long, but it isn\'t working. Here is the code

#include
#include

        
相关标签:
4条回答
  • 2020-11-30 11:17

    %lld is the standard C99 way, but that doesn't work on the compiler that I'm using (mingw32-gcc v4.6.0). The way to do it on this compiler is: %I64d

    So try this:

    if(e%n==0)printf("%15I64d -> %1.16I64d\n",e, 4*pi);
    

    and

    scanf("%I64d", &n);
    

    The only way I know of for doing this in a completely portable way is to use the defines in <inttypes.h>.

    In your case, it would look like this:

    scanf("%"SCNd64"", &n);
    //...    
    if(e%n==0)printf("%15"PRId64" -> %1.16"PRId64"\n",e, 4*pi);
    

    It really is very ugly... but at least it is portable.

    0 讨论(0)
  • 2020-11-30 11:26

    First of all, %d is for a int

    So %1.16lld makes no sense, because %d is an integer

    That typedef you do, is also unnecessary, use the type straight ahead, makes a much more readable code.

    What you want to use is the type double, for calculating pi and then using %f or %1.16f.

    0 讨论(0)
  • 2020-11-30 11:26
        // acos(0.0) will return value of pi/2, inverse of cos(0) is pi/2 
        double pi = 2 * acos(0.0);
        int n; // upto 6 digit
        scanf("%d",&n); //precision with which you want the value of pi
        printf("%.*lf\n",n,pi); // * will get replaced by n which is the required precision
    
    0 讨论(0)
  • 2020-11-30 11:27
    • Your scanf() statement needs to use %lld too.
    • Your loop does not have a terminating condition.
    • There are far too many parentheses and far too few spaces in the expression

      pi += pow(-1.0, e) / (2.0*e + 1.0);
      
    • You add one on the first iteration of the loop, and thereafter zero to the value of 'pi'; this does not change the value much.
    • You should use an explicit return type of int for main().
    • On the whole, it is best to specify int main(void) when it ignores its arguments, though that is less of a categorical statement than the rest.
    • I dislike the explicit licence granted in C99 to omit the return from the end of main() and don't use it myself; I write return 0; to be explicit.

    I think the whole algorithm is dubious when written using long long; the data type probably should be more like long double (with %Lf for the scanf() format, and maybe %19.16Lf for the printf() formats.

    0 讨论(0)
提交回复
热议问题