Hello I’m an amateur programmer, and to make it worse it has been a while since I’ve done any programming so I decided to refresh my memory with some easy Topcoder problems. The first one I did ended up being a segment fault, and right now that’s beyond what I can figure out for myself, can anyone help me understand where the segment fault came from. Here is the code.
vector<int> Bonuses (vector<int> points)
{
int totalPoints = 0;
for (int i = 0; i != points.size(); ++i)
{
totalPoints += points[i];
}
vector<int> percentage;
int percentageLeft = 100;
int truncatedPercentage;
for (int i = 0; i != points.size(); ++i)
{
truncatedPercentage = points[i]/totalPoints;
percentage.push_back(truncatedPercentage);
percentageLeft -= truncatedPercentage;
}
for (int i = 1;i <= percentageLeft; ++i)
{
percentage[percentage.size() - i] += 1;
}
return percentage;
}
You have a logic error in your program. Change this:
to this:
Otherwise the percentage will be almost always 0, and the
percentageLeftwill be 100. That is whypercentage[percentage.size() - i] += 1is segfaulting as AndersK already found before me. The index is typically negative.That said, I am uncertain on whether mixing pushbacks and direct assignments gives you the most readable code that you could have here.