Thread: sorting values in array issue

  1. #1
    Registered User
    Join Date
    Feb 2015
    Posts
    2

    Post 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. #2
    Registered User
    Join Date
    Mar 2010
    Posts
    583
    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 subscribe to a feed

Similar Threads

  1. Sorting issue...
    By alphasil in forum C Programming
    Replies: 3
    Last Post: 07-12-2012, 03:58 PM
  2. C Stock Sorting Program Issue
    By litebread in forum C Programming
    Replies: 18
    Last Post: 12-09-2011, 11:37 PM
  3. Sorting issue
    By Ssalty in forum C++ Programming
    Replies: 1
    Last Post: 05-18-2011, 10:03 AM
  4. compare issue while sorting
    By Micko in forum C++ Programming
    Replies: 1
    Last Post: 03-06-2004, 10:34 AM
  5. Replies: 2
    Last Post: 03-07-2002, 10:14 AM

Tags for this Thread