c++ - 为什么我的 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;
}
解决方案
这是您return third
声明的位置。当任何数字大于第一个数字时,它退出thirdhighestnum
函数并返回一个值。把它放在你的for
循环之外,它应该没问题。
推荐阅读
- stylus - 从手写笔变量评估规则
- c# - EF 核心使用通用工厂注册数据库上下文
- c# - 嵌套类
- : 如何访问列表中的嵌套类?
- python - 如何在 Pandas 列中将科学记数法转换为所需的小数
- ruby-on-rails - ActiveRecord::StatementInvalid: PG::UndefinedTable 在多对多关系中但表存在
- c - 在 Nucleo-F401RE 上使用 DMA 配置 ADC 会产生不稳定的值
- css - 在 2 个单独的表格中选择“selected”类的第一个和最后一个“td”元素
- javascript - react组件构造后如何让函数运行?
- php - 将表情符号从 php Web 应用程序传递到 Oracle db 和 mysql
- python - 当小数> = 1时,pandas / numpy round() 如何工作?