I have a program with 2 \"paired\" integer arrays newNumerator[ ], and newDenominator[ ] which both have 9 integers in them. I wrote a function that sorts them in ascending ord
The main error you have is that you are giving wrong values to static_cast<>
. Later you use them correctly by dereferencing, but in the cast you are missing that.
What you need is:
double percentageLeft = 100.0 * static_cast<double>((*newNumerator)[count]) / *newDenominator[count];
double percentageRight = 100.0 * static_cast<double>((*newNumerator)[count + 1]) / *newDenominator[count + 1];
Added parentheses to make it explicitly clear what the dereferencing is.
Also if you are not changing the actual array pointers, but only the contents of the arrays, you can remove the dereferencing hassle altogether. If you define the function as
void sortData(int newNumerator[], int newDenominator[], int newSize)
you can just use the normal indexing without dereferencing every time you use it.
You said:
I have a program with 2 "paired" integer arrays newNumerator[ ], and newDenominator[ ]
Yet your function defined as:
void sortData(int *newNumerator[], int *newDenominator[], int newSize)
I think that should be:
void sortData(int newNumerator[], int newDenominator[], int newSize)
If that is indeed the case, then the lines:
temp1 = *newNumerator[count];
*newNumerator[count] = *newNumerator[count + 1];
*newNumerator[count + 1] = temp1;
temp2 = *newDenominator[count];
*newDenominator[count] = *newDenominator[count + 1];
*newDenominator[count + 1] = temp2;
need to be:
temp1 = newNumerator[count]; // Remove the *
newNumerator[count] = newNumerator[count + 1];
newNumerator[count + 1] = temp1;
temp2 = newDenominator[count];
newDenominator[count] = newDenominator[count + 1];
newDenominator[count + 1] = temp2;
I propose using the STL for sorting. Makes things simpler and more understandable.
#include <vector>
#include <algorithm>
struct Ratio
{
int numerator;
int denominator;
double toDouble() const
{
return static_cast<double>(numerator)
/ static_cast<double>(denominator);
}
bool operator < (Ratio const& other) const
{
return toDouble() < other.toDouble();
}
};
void main()
{
std::vector<Ratio> ratios = { {1, 2}, {5, 7}, {2, 11} };
std::sort(ratios.begin(), ratios.end());
}
Dealing with raw arrays and sorting manually is almost always the more tedious and error prone approach.
See http://en.cppreference.com/w/cpp/algorithm/sort and http://en.cppreference.com/w/cpp/container/vector for reference