c - else if 语句阻止程序检测最大索引

标签 c

该程序的目的是检测命名数组中的最大数字。但目前它仅检测数组的最后一位数字。如果 else if 被删除或注释掉,那么它可以正确检测除最后一个数字之外的所有数字。

#include <stdio.h>

int main(){
    int c,i,max;

    printf("Enter the size of the array.");
    scanf("%d",&c);

    int array[c];

    printf("Enter the integers to fill the array.\n");
    for(i=0;i<c;i++){
        scanf("%d",&array[i]);
    }//end for

    int last_element = array[c-1];

    for(i=0;i<c;i++){
        printf("%d",array[i]);
        if(array[i-1] > array[i])  //This if statement detects greatest     
        {                          //index of array for all but last index 
            max = array[i-1];
        }//end if
        else if(last_element > array[i-1])  //This else if detects greatest
        {                                   //index of array in last index
            max = last_element;             //This statement is always eval
        }//end if                           //uating true.
    }//end for

    printf("\n%d",max);
    return 0;
}//end main

最佳答案

largest = array[0];            //consider your 1st element as largest element
for (i = 1; i < size; i++)     //
{
    if (largest < array[i])    //compare largest element with i'th element
        largest = array[i];    //if it is, make i'th element as largest
}
printf("\n largest element present in the given array is : %d", largest);

试试这个

关于c - else if 语句阻止程序检测最大索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46101786/

相关文章:

c - 根据第二个数组重新排列第一个数组时遇到问题

c - 进程终止不影响 waitpid()

c - 为什么无论输入是什么都会执行两个 if 语句?

c++ - Eclipse Cdt Indexer - 如何定位语法错误和未解析的名称

c - 去掉后面的二进制数但保持bitsize

c - 如何在 C 中引用 UTF-16 字符?

c - 尝试单步执行代码时 gdbserver 锁定

c - 在 Linux 上通过 WiFi 发送原始数据包 (C/C++)

c - 我怎么知道一个字符串是否以空结尾?

c - 如何在linux上写命令