Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to printf long long

Tags:

c

pi

long-integer

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<stdio.h> #include<math.h> typedef long long num; main(){     num pi;     pi=0;     num e, n;     scanf("%d", &n);     for(e=0; 1;e++){       pi += ((pow((-1.0),e))/(2.0*e+1.0));       if(e%n==0)         printf("%15lld -> %1.16lld\n",e, 4*pi);       //printf("%lld\n",4*pi);     } } 
like image 637
Carlos Avatar asked Jun 19 '11 02:06

Carlos


People also ask

How do I print long long int in printf?

Printing short, long, long long, and unsigned Types To print an unsigned int number, use the %u notation. To print a long value, use the %ld format specifier. You can use the l prefix for x and o, too. So you would use %lx to print a long integer in hexadecimal format and %lo to print in octal format.

Can we use %d for long?

You should scanf for a %ld if that is what you are expecting. But since a long is larger than your typical int , there is no issue with this.

How do I print long int?

You must use %ld to print a long int , and %lld to print a long long int . Note that only long long int is guaranteed to be large enough to store the result of that calculation (or, indeed, the input values you're using).

How do I print long long doubles?

%Lf format specifier for long double %lf and %Lf plays different role in printf. So, we should use %Lf format specifier for printing a long double value.


Video Answer


1 Answers

%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.

like image 108
karadoc Avatar answered Sep 21 '22 22:09

karadoc