Thread: sorting values in array issue

1. sorting values in array issue

so i tried sorting arr2 from lowest to highest value, but it only gives me 4 values and then the rest are zero. Any thoughts on how to fix this?

Code:
```#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
cout << fixed << setprecision(1);
float userMin;
float userMax;
const int SIZE = 21;
float arr[SIZE];
const int SIZE2 = 21;
float arr2[SIZE2];
int count = 0;
cout << "enter min ";
cin >> userMin;
cout << "enter max ";
cin >> userMax;
float inc = (userMax - userMin) / (SIZE-1);
float x = inc*count + userMin;
for (; x <= userMax;)
{
for (int e = 0; e < SIZE; e++)
{
arr[e] = x;
arr2[e] = (0.0572*cos(4.667*x) + 0.0218*cos(12.22*x));
cout << setw(15) << setprecision(1)<< arr[e]
<< setw(15) << setprecision(3) << arr2[e]
<< endl;
count++;
x = userMin + inc*count;
}
}
int temp;
for (int e = 0; e < SIZE-1; e++)
{
for (int j = e+1; j < SIZE; j++)
{
if (arr2[e] > arr2[j])
{
temp = arr2[e];
arr2[e] = arr2[j];
arr2[j] = temp;
}
}
}
for (int e = 0; e < SIZE; e++)
{
cout << "sorted: " << arr2[e] << endl;
}
return 0;
}```

2. Yeh, you have some truncaiton-to-integer issues here:
Code:
``` int temp;
for (int e = 0; e < SIZE-1; e++)
{
for (int j = e+1; j < SIZE; j++)
{
if (arr2[e] > arr2[j])
{
temp = arr2[e];
arr2[e] = arr2[j];
arr2[j] = temp;
}
}
}```
Whenever you assign a float to the integer temp, the sub-zero part is thrown away, which will obviously leave you with 0 for smal numbers.

IF you use a float fior temp you'll be fine.

Popular pages Recent additions