Reputation: 21
Basically all I'm trying to do is run a loop that returns the value of X/Y Mod 10 where X is 1234567890123456 and Y is 10^i, so that I can get each individual digit of 1234567890123456 separated. But after i = 7 it returns 11 instead of the correct value (9). All numbers involved are of the long data type. I've tried doing it with the pow() function, and manually by just inputting the powers of ten and still get the same result.
#include <stdio.h>
#include <math.h>
long Cardno;
long Digits;
long Divider;
int main(void)
{
Cardno = 1234567890123456;
Digits = log10(Cardno) +1;
if (Digits == 13 || Digits == 15 || Digits == 16)
{
for(int i = 0; i <= Digits; i++)
{
printf("%lo\n", Cardno/10000000 % 10);
}
}
else
{
printf("INVALID\n");
}
}
Upvotes: 2
Views: 111
Reputation: 1841
so you have to use long long
instead of long
, I don't why the compiler didn't give this warning , but the compiler of mine gave me this warning :
Implicit conversion from 'long long' to 'long' changes value from 1234567890123456 to 1015724736
also variable called Digits
doesn't need to be long , int
will work just fine.
also , function called log10()
takes double
and returns double
so you have to cast that.
also in your code you are printing Cardno/10000000 % 10
which is wrong , it sould be (Cardno/ (long long )pow(10, i)) % 10
and here is the full code :
#include <stdio.h>
#include <math.h>
long long Cardno;
int Digits;
long long Divider;
int main(void)
{
Cardno = 1234567890123456;
Digits = (int)log10((double )Cardno) +1;
if (Digits == 13 || Digits == 15 || Digits == 16)
{
for(int i = 0; i <= Digits; i++)
{
printf("%ld\n",(Cardno/ (long long )pow(10, i)) % 10);
}
}
else
{
printf("INVALID\n");
}
}
Upvotes: 2