Reputation: 185
so what I am trying to do is take a vector of numbers, find the number of time each element occurs then calculate the percentage equivalent of its number of occurances in the vector.
it works perfectly well on a vector with a few elements of only one number but not at all with a vector of different elements (2 to be exact) occuring multiple times.
here is a detailed output:
count = 6
pushed back 21
total = 6
percent = 6 / 6* 100
pushed back 100
Number:
21
Percent Chance
100
count = 5
pushed back 42
count = 5
pushed back 21
total = 5
total = 10
percent = 5 / 10* 100
pushed back 0
percent = 5 / 10* 100
pushed back 0
Number:
42
Percent Chance
0 // SHOULD BE 50
Number:
21
Percent Chance
0 // SHOULD BE 50
Here is the Code: (the output is from this function running twice with a different x vector)
std::vector <std::string> findpercentages(std::vector <std::string> x)
{
int count{}; //for amount of times element occurs
std::vector <std::string> tempvec{}; //to hold the element/s
std::vector <int> counts{}; //to hold count for each element in tempvec
std::vector <std::string> finalvec{}; //elements and counts of elements
for (size_t i = 0; i < x.size(); i++)
{
//look for x[element] in tempvec, if not in tempvec, count occurances in x and add element to
// tempvec, add count to counts
std::vector <std::string>::iterator point { std::find(tempvec.begin(), tempvec.end(), x[i]) };
if (point == tempvec.end())
{
count = std::count(x.begin(), x.end(), x[i]);
std::cout << "count = " << count << '\n';
counts.push_back(count);
std::cout << "pushed back " << x[i] << '\n';
tempvec.push_back(x[i]);
}
}
int total{};
for (size_t n = 0; n < counts.size(); n++)
{
total += counts[n]; //total for percentage calculation
std::cout << "total = " << total << '\n';
}
for (size_t y = 0; y < tempvec.size(); y++)
{
finalvec.push_back(tempvec[y]);
//percent calculation. used unsigned_int64 because got arithmatic overflow warning if i just use
// int
unsigned __int64 percentage = static_cast <unsigned __int64> (round((counts[y] / total) * 100));
std::cout << "percent = " << counts[y] << " / " << total << "* 100" << '\n';
finalvec.push_back(std::to_string(percentage));
std::cout << "pushed back " << percentage << '\n';
}
return finalvec;
}
Upvotes: 0
Views: 418
Reputation: 87944
unsigned __int64 percentage = static_cast <unsigned __int64> (round((counts[y] / total) * 100));
should be something like
double percentage = round((100.0 * counts[y]) / total);
Your problem is that when you divide one integer by another you always get a integer. So (counts[y] / total)
is always going to be 0
or 1
.
So the simplest solution is to introduce a double
value 100.0
into the calculation. This makes sure that you get floating point division instead of integer division.
Upvotes: 2