这个是学校功课,老师限制不让用array。
这个program的用法是输入一串价格,最后输入-1,然后就会output最大利润。
例如我输入20,10,30,40,-1,前面几个数字分别代表第一天第二天第三天第四天股票的价格,
那么假设我在第二天买进,第四天卖出,我将获得最大利润(40-10)=30。
现在我唯一的问题是我写的代码处理不了这种情况,例如
我输入20,30,10,我这个program会把10当成最小值,然后output最大利润为
(30-10),请问各位能帮我修改代码,避免这种错处吗?
或者有其他代码能够完成这个作业?
``
#include
using namespace std;
int main(){
int c(0),r(0),n1(0),min(0),max(0),l(0),s(0);
cout<<"Please enter the prices: ";
while(n1!=-1){
cin>>n1;
if(min==0 && n1>0)
{min=n1;}
c++;
if(n1<=0 && n1!=-1) {cout<<"Invalid. Input again. Please make sure it's a positive number!"<<endl;r++;}
else {
if(n1<min && n1!=-1 && c<=l) {min=n1; s++;}
if(n1>=max && (c-r)>(s+1)) {max=n1; l=c;}
cout<<c<<s+1<<l<<endl;
}
}
cout<<max<<min;
cout<<endl<<"Largest amount earned: "<<(max-min)<<endl;
return 0;
}