I have a code in which I enter a 12 or 13 digit number and it does a few calculations here and there, then it spits out the barcode again with a few extra details.
When I enter a 13 digit number it works fine, and before I "fixed" my code, at least it was taking in a 12 digit number and spitting out the wrong values, but now it just says "floating point error".
What is this, and where exactly am I going wrong?
Code:
#include <stdio.h>
#include <assert.h>
#define UPPER_LIMIT 10000000000000LL
#define LOWER_LIMIT 100000000000LL
int main(int argc, char *argv[]) {
long long barcode = 0;
int partOne = 0;
int partTwo = 0;
int partThree = 0;
int partFour = 0;
int numScanned = -1;
long long i = 0;
long long j = 0;
int subTotal = 0;
int sumEven = 0;
int sumOdd = 0;
int checkSum = -1;
int digitFlag = 0;
printf("Enter barcode: ");
numScanned = scanf("%lld", &barcode);
assert( (numScanned == 1) && ((barcode / LOWER_LIMIT) != 0) );
partOne = barcode / 10000000000LL;
partTwo = ( barcode / 10000 ) % 1000000;
partThree = ( barcode / 10 ) % 1000;
partFour = barcode % 10;
//checksum for 12 digit barcode
if ( (barcode / (10*LOWER_LIMIT)) == 0 ) {
for ( i = LOWER_LIMIT; i >= 0; i = i/100 ) {
subTotal = (barcode / i) % 10;
sumEven = sumEven + subTotal;
//printf("sumeven %d\n", sumEven);
}
for ( j = LOWER_LIMIT / 10; j > 0; j = j/100 ) {
subTotal = 3 * ( (barcode / j) % 10);
sumOdd = sumOdd + subTotal;
//printf("sumodd %d\n", sumOdd);
}
checkSum = (sumOdd + sumEven) % 10;
if (checkSum != 0) {
checkSum = 10 - checkSum;
}
digitFlag = 12;
} else { //checksum for 13 digit barcode
for ( i = 10 * LOWER_LIMIT; i > 10; i = i/100 ) {
subTotal = (barcode / i) % 10;
sumEven = sumEven + subTotal;
printf("sumeven %d\n", sumEven);
}
for ( j = LOWER_LIMIT; j > 0; j = j/100 ) {
subTotal = 3 * ( (barcode / j) % 10);
sumOdd = sumOdd + subTotal;
printf("sumodd %d\n", sumOdd);
}
checkSum = (sumOdd + sumEven) % 10;
if (checkSum != 0) {
checkSum = 10 - checkSum;
}
digitFlag = 13;
}
printf("\nBarcode is ");
//print the 12 digit barcode with the checksum
if (digitFlag == 12) {
printf("%d-%06d-%03d-%d\n", 10*partOne + partTwo/100000,
10*(partTwo % 100000) + partThree/100,
10*(partThree % 100) + partFour,
checkSum);
} else if (digitFlag == 13) { //print 13 digit barcode and check valid
printf("%d-%06d-%03d-%d\n", partOne, partTwo, partThree, partFour);
printf("Checksum is %d\n", checkSum);
if (checkSum == partFour) {
printf("Barcode is valid\n");
} else {
printf("Barcode is invalid\n");
}
}
return 0;
}