【问题标题】:How to print out the position of a value of an array?如何打印出数组值的位置?
【发布时间】:2021-12-23 08:23:39
【问题描述】:
int smallest = array[0];
int pos = 0;

for (int x = 0; x < 10; x++) {
    if (array[x] < smallest) smallest = array[x];
    pos = x;
}

printf ("%d is the smallest number and its located in %d\n", smallest, pos);
printf ("\n");

int largest = array[10];
int position = 0;

for (int y = 0; y < 10; y++) {
    if (array[y] > largest) largest = array[y];
    position = y;
}

printf ("%d is the largest number and its located in %d\n", largest, position);

我在这里尝试的方法不起作用,当我编译并运行它时,它每次都会给我最大和最小数组的位置 9。

【问题讨论】:

  • 提供最小的完整程序。这个赋值 int large = array[10];调用未定义的行为。

标签: arrays c for-loop max min


【解决方案1】:

此声明中的初始化

int largest = array[10];

如果数组有 10 个元素,则调用未定义的行为。

同样在这个 if 语句中

    if (array[x] < smallest) smallest = array[x];
        pos = x;

您需要使用复合语句,如

    if (array[x] < smallest)
    {
        smallest = array[x];
        pos = x;
    }

或逗号操作符

    if (array[x] < smallest) smallest = array[x], pos = x; 

一般方法如下。

size_t pos = 0;

for ( size_t i = 1; i < sizeof( array ) / sizeof( *array ); i++ )
{
    if ( array[i] < array[pos] ) pos = i;
}

printf("%d is the smallest number and its located in %zu\n", array[pos], pos);

pos = 0;

for ( size_t i = 1; i < sizeof( array ) / sizeof( *array ); i++) 
{
    if ( array[pos] < array[i] ) pos = i;
}

printf( "%d is the largest number and its located in %zu\n", array[pos], pos );

您可以将两个 for 循环组合到一个 for 循环中,定义两个用于存储位置的变量。例如

size_t pos_min = 0, pos_max = 0;

for ( size_t i = 1; i < sizeof( array ) / sizeof( *array ); i++) 
{
    if ( array[i] < array[pos_min] ) pos_min = i;
    else if ( array[pos_max] < array[i] ) pos_max = i;
}

因此array[pos_min] 代表最小元素,array[pos_max] 代表最大元素。

【讨论】:

  • 不好。真实的是smallest = array[x] &lt; smallest ? array[pos = x] : smallest
  • @АлексейНеудачин 这是一个可读性较差的代码。
  • 如果你提到逗号哈哈
  • @АлексейНеудачин 我展示了如何重写 if 语句以使其至少正确。
猜你喜欢
  • 1970-01-01
  • 2016-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多