简体   繁体   English

我的 C++ 代码中有一个奇怪的错误

[英]There's a strange bug in my c++ code

Our professor want us to write some code to do some calculate about financial instrument, buy low and sell high.and the prices change as time.我们的教授要我们写一些代码来计算金融工具,低买高卖,价格随时间变化。 for example, the input is {1,2,4} so we are able to buy 1 and sell as 2, and buy 2 sell 4. so the output should be 1+2=3.例如,输入是 {1,2,4},所以我们可以买 1 卖 2,买 2 卖 4。所以输出应该是 1+2=3。 And if the input is {4,2,1} we are not able to buy low and sell high.如果输入是 {4,2,1},我们就不能低买高卖。 so the out put should be 0. and here's my code.所以输出应该是0。这是我的代码。

#include<iostream>
#include<vector>

using namespace std;

int getMaxProfit(vector<int> &prices)
 {
int p;
int n=0;
vector<int> profits;

if(prices.size()==1)
{
    return 0;
}

for(int i=0; i<prices.size();i++)
{
    if (prices[i]<prices[i+1])
    {
        p=prices[i+1]-prices[i];
        profits.push_back(p);
    }

}

for(int i=0; i<profits.size();i++)
{
    n=n+profits[i];

}


return n;
}

int main()
{
vector<int> prices = {1,2,4};

cout<<getMaxProfit(prices);

return 0;
}

it works pretty well when there's only 4 or less value in my input.当我的输入中只有 4 个或更少的值时,它工作得很好。 However if there's more than 4 values, like {1,1,2,3,4}.但是,如果有超过 4 个值,例如 {1,1,2,3,4}。 I will get the wrong answer.我会得到错误的答案。 I cant fig out what's wrong about it.我无法弄清楚它有什么问题。

Ok, I got it.好,我知道了。 Changed a little about my code and it worked.对我的代码进行了一些更改,它起作用了。

#include<iostream>
#include<vector>

using namespace std;

int getMaxProfit(vector<int> &prices)
{
int p;
int n=0;
vector<int> profits;

if(prices.size()==1)
{
    return 0;
}
p = prices[0];
for(int i=1; i<prices.size();i++)
{
    if (p<prices[i])
    {
        n=prices[i]-p;
        profits.push_back(n);
        p=prices[i];
    }
    else
    {
        p =prices[i];
    }
}
n=0;

for(int i=0; i<profits.size();i++)
{
    n=n+profits[i];

}


return n;
}

int main()
{
vector<int> prices = {3,1,5,2,4};

cout<<getMaxProfit(prices);

return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM