首页 > 解决方案 > 为什么我的 for 循环只运行 2 次而不是 10 次?

问题描述

我试图在具有 O(n) 空间和时间复杂度的数组中找到第三高的数字。我的程序显然是错误的,但这不是问题。我在函数中的 for 循环thirdhighestnum似乎只运行了 2 次。我似乎找不到它的原因。谁能帮我。抱歉,我是这里的初学者。

#include<iostream>

using namespace std;

int thirdhighestnum(int a[],int size)
{ 
    cout<<" "<<size<<endl;
    int first=a[0],second=0,third=0;
    for(int i=1;i<size;i++)
    {
        cout<<a[i]<<";"<<endl;
        if(a[i]>first)
        {
            first=a[i]; 
            if(a[i+1]>first)
            {
                second=first;
                first=a[i+1];
                if(a[i+2]>first)
                {   third=second;
                    second=first;   
                    first=a[i+2];

                }
            }
            cout<<i<<endl
            return third;
        }
    }
}
int main()
{  int num,a[10];
    cout<<"Enter the elements in the array"<<endl;
    for(int i=0;i<10;i++)
        cin>>a[i];
    cout<<"Third highest number is "<<thirdhighestnum(a,10)<<endl;
    return 0;
}

标签: c++

解决方案


这是您return third声明的位置。当任何数字大于第一个数字时,它退出thirdhighestnum函数并返回一个值。把它放在你的for循环之外,它应该没问题。


推荐阅读