I am working on a CSV file that I got from yahoo finance, which has information about the prices on the stock of AAPL. I am trying to display the first five greatest percent change that increased the most of that file.
for the percent change, I used:
s[x].percent_change = (s[x].adj_close2 - s[x].open2) / s[x].open2 * 100;
as my formula, which worked.
then I coded this:
double original = s[0].percent_change;
int maximum = 0;
//Loop that computes the stock whose percentage change increased the most
for (int i = 0; i < lines; i++) {
if (s[i].percent_change > original) {
original = s[i].percent_change;
maximum = i;
}
}
cout << "\n\nThe greatest percent change is the date: " << endl;
cout << s[maximum].date << endl;
cout << s[maximum].adj_close << endl;
cout << s[maximum].percent_change << endl;
which again, worked, to get the stock whose percentage change increased the most
but the thing is, I cannot figure out what to do next after this.
How could I get the other four greatest results of the CSV file? I tried modifying the loop and adding another loop, but those loops did not work.
I am still learning c++, please be as simple as you can.
答案 0 :(得分:0)
我认为这应该有效。但是,这是一种幼稚的方法。
double original[5];
for (int i = 0; i <5; i++){ #save the first 5 entries
original[i] = s[i].percent_change;
}
int maximum[5] = {0,1,2,3,4};
//Loop that computes the stock whose percentage change increased the most
for (int i = 5; i < lines; i++) { #we can ignore the first 5 lines here
for (int j = 0; j < 5 ; j++) {
if (s[i].percent_change > original[j]) {
original[j] = s[i].percent_change;
maximum[j] = i;
break;
}
}
}
请注意,如果s中的元素少于5个,则会失败。
答案 1 :(得分:0)
C ++ STL中有排序方法。 因此,使用它会更好。 这是示例。
#include <algorithm>
#include <vector>
struct Row {
float percent_change;
};
bool compareRow(const Row& a, const Row& b) {
return a.percent_change > b.percent_change;
}
sort(s.begin(), s.end(), compareRow);
for (int i=0; i<5; i++) {
cout << s[i].percent_change << endl;
}
也许最好检查一下此页面 https://www.geeksforgeeks.org/sorting-a-vector-in-c/