我试图从一系列整数值中打印前两位数字。但是在选择每个值并将它们存储在数组中之后。当我尝试打印值时,数组倾向于只存储正确的前四个值,然后其余的值变得奇怪。这是我在
下面的代码#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("%dn", arr[i]);
count++;
}
}
输出:
3
6
8
8
7
0
9
credit/ $
当d
为100000000
时,第5次迭代时d = d * 100
出现算术溢出,且乘法超出int
类型的范围。将类型更改为long
或long long
将解决此问题。
类型long
在您的机器上可能有64位,但为了可移植性,您应该使用long long
或unsigned long long
来代替credit
和d
。
如果使用稍微不同的方法,代码可能会更容易理解,其中除法而不是乘数。
修改后的版本:
#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("%dn", arr[i]);
}
}
最有可能发生的是您没有为credit
使用足够大的整数类型。虽然在某些系统上,long
足够大,可以容纳63位整数(如果unsigned
是64位),但C标准只要求它足够大,可以容纳31位整数(如果unsigned
是32位)。您试图存储到credit
中的数字是一个45位整数,可能太大,因此被截断为较小的数字。
如果是这个问题,您需要切换到更大的整数类型。long long
需要足够大。您还可以包含stint .h并显式使用64位整数类型:uint64_t
。