传递给函数的变量未设置为我分配给它的值

Variable passed to function isn't set to the value I assigned to it

为了return给定数字左边的第 i 个数字,我创建了这个函数:

int ith(unsigned long x, int i)
{
    int count=0;
    unsigned long y = x;

    do
    {
        y /= 10;
        count++;
    } while (y > 0);
    if (i > count)
        return -1;
    count -= i;
    while (count > 0)
    {
        x /= 10;
        count--;
    }
    return x % 10;

}

但是,当函数的输入为 2,2 时。函数完成需要很长时间; 所以我查看了调试器,发现 count==54353453count 从未收到我分配给他的 0

编辑 这是我的其余代码,一些建议可能是此错误的根源。

int main()
{
    int x, i,result;
    do
    {
        printf("Enter a number and the digit you want to retrieve.\nEnter a negative number to exit\n");
        scanf("%ul %d", &x, &i);
        if (x<0)
        {
            printf("Operation Aborted.. Exiting....\n");
            break;
        }
        else
        {
            result = ith(x, i);
            if (result == -1)
            {
                printf("Error: There are no such amount of digits to retrieve from that location\n");
                continue;
            }
            printf("The %dth digit of the number %ul is %d\n", i, x, result);
        }

    } while (x >= 0);
}

这一行

scanf("%ul %d", &x, &i);

x 中使用了错误的扫描说明符。

因为 x 被定义为 int,它必须是

scanf("%d %d", &x, &i);

或者您将 x 定义为 unsigned long 那么它必须是

scanf("%lu %d", &x, &i);

同样的问题在这里:

printf("The %dth digit of the number %ul is %d\n", i, x, result);