yobro97 yobro97 - 3 months ago 16
C Question

Finding a decimal value truncated to k decimal places

Given an integer

k
, it is expected to find the value of the fraction
103993/33102
, truncated upto
k
decimal places. So my approach was the following:

int k ;
scanf("%d",&k);
printf("3");
if(k>0)
printf(".");
long long int num=30;
long long int numer = 1039930;
long long int denom = 33102;
while(k--)
{
long long int bro = numer/denom;
printf("%lld",bro-num);
num=bro;
num*=10;
numer*=10;
}


But if
k
is
20
it is showing a weird answer....any problems in the loop?

http://ideone.com/dndib2

Answer

Your problem is overflow.

with num *= 10; and numer *= 10; in your loop, looping 20 times means 10 ^20 (10 to the power of 20) and with long long int being 64 bits it can hold a maximum of 18,446,744,073,709,551,615 (2^64-1) which is less than 10^20.