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

标签 c memory variable-assignment

为了返回给定数字左边的第 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);

关于c - 传递给函数的变量未设置为我分配给它的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31741223/

相关文章:

c - Linux C 中带有 pthreads 的 Openmp 并行 for 循环语法

c - 在 C 中传递和使用可变数量的参数来运行函数

ruby - 如何使用非常大的 Ruby 哈希减少内存使用量?

python - 为什么两个变量的值在 Python 中都会发生变化?

objective-c - 双重赋值在 Objective-C 中有效吗?

c - 证明 : Pythagorean Triple algorithm is faster by Euclid's Formula?

c - 从switch重写为if else

azure - 如何在 Azure VMSS 中定义内存自动缩放规则

windows - VMMap 如何知道给定的内存区域是线程堆栈,具体来说?

c# - 在 if 语句中分配变量 C#