am trying to print first two digit from a series of an integer value. but after selecting each of the values and storing them in an array. when i try to print the values the array tend to only store correctly the first four value and afterwards the rest of the value becomes strange. this is my code below
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int main(void)
{
long credit = 24681482846434;
int mid_length = (14 / 2); // length of array
int arr[mid_length];
int d = 100;
int count = 1;
//loop to get the first second numbers
for (int i = mid_length - 1; i >= 0; i--) {
arr[i] = (credit % d) / (d / 10);
d = d * 100;
printf("%d\n", arr[i]);
count ;
}
}
this the output:
3
6
8
8
7
0
9
credit/ $
CodePudding user response:
There is an arithmetic overflow in d = d * 100
at the 5th iteration when d
is 100000000
and the multiplication exceeds the range of type int
. Changing the type to long
or long long
will fix this issue.
Type long
probably has 64 bits on your machine, but for portability, you should use long long
or unsigned long long
for credit
and d
.
The code might be somewhat easier to follow with a slightly different method where you divide the number instead of multiplying the divisor.
Here is a modified version:
#include <stdio.h>
int main() {
long long credit = 24681482846434;
int mid_length = (14 1) / 2; // length of array
int arr[mid_length];
//loop to get the first digit of digit pairs
long long temp = credit;
for (int i = mid_length; i --> 0;) {
int pair = temp % 100;
temp /= 100;
arr[i] = pair / 10;
printf("%d\n", arr[i]);
}
}
CodePudding user response:
What's most likely happening is you're not using a sufficiently large integer type for credit
. While, on some systems, long
is big enough to hold 63-bit integers (64-bit if unsigned
), the C standard only requires that it be big enough to hold 31-bit integers (32-bit if unsigned
). The number you're trying to store into credit
is a 45-bit integer which is probably too big and, therefore, is being truncated down to a smaller number.
If that's the issue, you'd need to switch to a larger integer type. long long
is required to be big enough. You can also include stdint.h and explicitly use a 64-bit integer type: uint64_t
.