首页 > 解决方案 > 使用模数运算符时函数返回奇怪的值

问题描述

它在前几次迭代中运行良好,但之后它开始将最后一位数字更改为我知道不正确的数字。这是代码:

long long isbnToArray(long long userNum)
{

int i;
char isbnArray[20];
for (i = 0; i <12; i++)
{
    long long userNumFirst;
    long long userNumRem;
    int j = 11 - i;  // gives us the power of 10 required for the divisor/ modulus operators
    long long int divR = pow(10.0, j);

    userNumFirst = userNum / divR;  // value of the first digit
    userNumRem = userNum % divR;  // remainder after division
    isbnArray[i] = userNumFirst;  // inputs the first ISBN digit value into the array
//    printf("%d.", isbnArray[i]);
    userNum = userNumRem; // sets the isbn number as the remainder for the next iteration of the loop, eg 123451234512 becomes 23451234512.

    printf("userNum = %lli\n", userNum);
}
}

在第二次迭代之后,当最后一个数字应该保持为“2”时,它会变成“5”,然后它会螺旋上升。我不知道为什么。

运行时,值为:

userNum = 23451234512(预期)

userNum = 3451234512(预期)

userNum = 451234515(预期 451234512)

userNum = 51234519(预期 51234512)

userNum = 1234524(预期 1234512)

userNum = 234524(预期 234512)

userNum = 34524(预期 34512)

userNum = 4527(预期 4512)

userNum = 527(预期 512)

userNum = 32(预期 12)

userNum = 2(预期为 2)

userNum = 0(预期为 0)

标签: c

解决方案


推荐阅读