最小值无法识别

The minimum value is not recognize

识别出最大值但识别不到最小值?你能帮我找出这段代码中的问题吗?还是编译器有问题?

#include<stdio.h>

int main()
{
    int e,i,sval,lval;

    printf("\nInput the length of the array:");
    scanf("%d", &e);

    int v[e];
    printf("\nInput the array element:\n");

    for(i=1; i<=e; i++)
    {
        scanf("%d", &v[i]);
    }
    for(i=1; i<=e; i++)
    {
        if(sval > v[i])
        {
            sval = v[i];
        }
        else
        {
            lval = v[i];
        }

    }

    printf("Smallest value : %d\n", sval);
    printf("Larger value : %d\n", lval);

    return 0;
}

基于 C 的数组为 0

int v[e];
printf("\nInput the array element:\n");

for(i=1; i<=e; i++)
{
    scanf("%d", &v[i]);
}

此处:i<=e您正在访问数组边界之外,切换到

for(i=0; i<e; i++)
{
    scanf("%d", &v[i]);
}

相同
for(i=1; i<=e; i++)
{
    if(sval > v[i])
    {
        sval = v[i];
    }
    else
    {
        lval = v[i];
    }

}

使用前初始化变量svallval

int e,i,sval = 0,lval = 0;

此代码存在一些问题:

  1. C 中的数组从索引 0 开始,因此我们需要在几个地方进行调整。
  2. 需要适当地初始化最小值和最大值。
  3. 在循环中确定哪个值是 smallest/largest 时存在逻辑问题。

请查看内联评论。

#include <limits.h>
#include <stdio.h>

int main()
{
    int e, i, min_val, max_val;
    min_val = INT_MAX;
    max_val = INT_MIN;
    // Need to initialize these to min/max values
    // We set the smallest value to the largest value because
    // presumably all other values will be lower than this. 
    // The same is true for the larger value.

    printf("\nInput the length of the array:");
    scanf("%d", &e);

    int v[e];
    printf("\nInput the array element:\n");

    // as mentioned, arrays start at 0
    for(i = 0; i < e; i++)
    {
        scanf("%d", &v[i]);
    }
    for(i = 0; i < e; i++)
    {
        if (min_val > v[i]) {
            min_val = v[i];
        }
        // Need a separate condition here, not an else.
        // In your example, you had the statement:
        // "If the value I am currently looking at is smaller than
        // my currently known smallest value, assign it to the larger
        // value" <- this is a logic flaw. It becomes apparent in sets
        // such as the one shown: [9, 8, 2, 6]
        // In your example, when we reach the iteration
        // where we are looking at the 6, since that is larger
        // than the currently known smallest value of 2, we would 
        // assign the 6 to the largest value, when it should be 9.
        if (max_val < v[i]) {
            max_val = v[i];
        }
    }

    printf("Smallest value : %d\n", min_val);
    printf("Larger value : %d\n", max_val);

    return 0;
}
(venv) [ttucker@zim Whosebug]$ gcc -o min_max min_max.c 
(venv) [ttucker@zim Whosebug]$ ./min_max 

Input the length of the array:4

Input the array element:
9
8
2
6
Smallest value : 2
Larger value : 9