如何将数组中的第一个元素分配给变量?

时间:2018-11-06 02:41:14

标签: c arrays

我是c的新手,我对c中的数组有麻烦。我不知道如何将数组中的第一个元素分配给一个int变量。当我尝试时,我什至没有索引就在范围内得到一个随机的大整数。

这是我的代码的一部分:

int solve(int *elev, int n)
{
    for (int i = 0; i < n; ++i)
        printf("%d ", elev[i]);
    putchar('\n');

    printf("%d %d %d %d %d\n", elev[0], elev[1], elev[2], elev[3], elev[4]);

    int low = elev[0];
    int high = elev[4];

    printf("low:%d high:%d\n");

    // ...
}

部分输出:

1 4 20 21 24
1 4 20 21 24
low: 362452 high: 7897346

产生上述输出的原因是什么?

1 个答案:

答案 0 :(得分:4)

在这行上,您似乎没有将highprintf()变量作为参数传递给printf("low:%d high:%d\n")调用:

low

如果提供highprintf()变量作为printf("low:%d high:%d\n", low, high); 的参数,则应将预期的输出打印到控制台,如下所示:

"low:%d high:%d\n"

传递给printf()函数的%d的“打印格式”指出,格式字符串中每次出现%d时都会显示数值。

为了指定每次出现printf()时将显示的实际值,必须向%d函数提供附加参数-每次出现printf("low:%d high:%d\n", low, /* <- the value of low will be printed after "low:" in output the string */ high /* <- the value of low will be printed after "low:" in output the string */ ); 时要提供一个参数:< / p>

%d

如果未提供这些其他参数,则程序仍将编译并运行,但是,在运行时,程序将基本上显示在其希望为每个{发生了{1}}次。

有关printf()的更多信息,您might like to see this documentation-希望能有所帮助!

相关问题