【问题标题】:How to assign first element in array to a variable?如何将数组中的第一个元素分配给变量?
【发布时间】:2018-11-06 02:41:13
【问题描述】:

我是 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

上述输出的原因是什么?

【问题讨论】:

  • 除了 Dacre 的回答之外,我会删除第二条 printf 语句以支持动态 for 循环——假设您只是在测试?而high 很可能是elev[n-1](假设n>0 和elev[] 已排序)

标签: c arrays


【解决方案1】:

您似乎没有在这一行将 lowhigh 变量作为参数传递给 printf() 调用:

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

如果您将 lowhigh 变量作为参数提供给 printf(),则应将预期输出打印到控制台,如下所示:

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

传递给printf() 函数的"low:%d high:%d\n" 的“打印格式”表明,在格式字符串中每次出现%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 */
);

如果未提供这些附加参数,程序仍将编译和运行,但是,在运行时,程序将基本上显示在内存位置找到的任何值,它希望为每个 @ 找到值987654337@ 次。

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

【讨论】:

  • @Yunnosch 感谢您的反馈! - 刚刚更新了答案,你怎么看? :-)
猜你喜欢
  • 1970-01-01
  • 2013-05-28
  • 2021-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多