Finding max value in an array

后端 未结 5 938
闹比i
闹比i 2021-01-07 13:57
int highNum = 0;
int m;
int list[4] = {10, 4, 7, 8};
    for (m = 0 ; m < size ; m++);
    {
        if (list[m] > highNum)
            highNum = list[m];
             


        
相关标签:
5条回答
  • 2021-01-07 14:31
    int highNum = 0;
    int m;
    int list[4] = {10, 4, 7, 8};
        for (m = 0 ; m < size ; m++);    // <-- semicolon?
        {
            if (list[m] > highNum)
                highNum = list[m];
                cout << list[m];
        }
    cout << highNum;
    

    Looking at your indentation, you may have missed a pair of { ... } for the if statement as well.

    0 讨论(0)
  • 2021-01-07 14:33

    There is a ; right after the closing parentheses of your for loop: for (m = 0 ; m < size ; m++);

    The statements inside the block (inside the curly braces) gets executed only after the loop do nothing for size number of times and that too only once.

    You have also missed a pair of { ... } for the if statement as well.

    0 讨论(0)
  • 2021-01-07 14:34

    You put a superfluous at the end ; in :

    for (m = 0 ; m < size ; m++);
    

    Edit : Working code with some additional << endl;

    int size = 4;
    int highNum = 0;
    int m;
    int list[4] = {10, 4, 7, 8};
    for (m = 0 ; m < size ; m++)
    {
        if (list[m] > highNum)
            highNum = list[m];
        cout << list[m] << endl;
    }
    cout << highNum << endl;
    
    0 讨论(0)
  • 2021-01-07 14:35

    You have a semicolon after your for statement:

    for (m = 0 ; m < size ; m++);
    {
    

    This should be:

    for (m = 0 ; m < size ; m++)
    {
    
    0 讨论(0)
  • 2021-01-07 14:36

    Unless you're doing this for homework and have to write the loop, just use std::max_element, as in:

    int list[4] = {10, 4, 7, 8};
    std::cout << *std::max_element(list, list+4);
    

    ...or better, avoid hard-coding the length:

    int list[] = {10, 4, 7, 8};
    std::cout << *std::max_element(std::begin(list), std::end(list));
    
    0 讨论(0)
提交回复
热议问题