OpenMP截断浮点数

时间:2017-03-26 04:34:08

标签: c++ openmp

我正在从CSV文件中将数据(1维/矢量)读入float数组并应用 快速排序 在它上面:

int main()
{

float floatArr[2000];

ReadRandomData(floatArr, "D:\RandomData.csv");

//#pragma omp parallel
{
    QuickSort(floatArr, 0,2000);
}

for(int i=0; i<2000; i++)
{
    cout<<floatArr[i]<<endl;
}

_getch();

}

和输出是这样的:

enter image description here

但是一旦我取消注释#pragma omp parallel部分,输出就像这样(我认为它截断了)

enter image description here

任何人都可以解释我为什么会发生OpenMP以及如何解决这个问题?提前致谢!

更新

这是 QuickSort 部分:

void QuickSort(float* arr, int startIndex, int endIndex)
{
    int pivot = arr[startIndex];                    //pivot element is the leftmost element
    int splitPoint;

if(endIndex > startIndex)                        //if they are equal, it means there is only one element and quicksort's job here is finished
{
    splitPoint = Splitarr(arr, pivot, startIndex, endIndex);
                                                  //Splitarr() returns the position where pivot belongs to
    arr[splitPoint] = pivot;
    QuickSort(arr, startIndex, splitPoint-1);   //Quick sort first half
    QuickSort(arr, splitPoint+1, endIndex);  //Quick sort second half
}

}

这里是拆分代码:

int Splitarr(float* arr, int pivot, int startIndex, int endIndex)
{
    int leftBoundary = startIndex;
    int rightBoundary = endIndex;

while(leftBoundary < rightBoundary)            //shuttle pivot until the boundaries meet
{
     while( pivot < arr[rightBoundary]        //keep moving until a lesser element is found
            && rightBoundary > leftBoundary)      //or until the leftBoundary is reached
     {
          rightBoundary--;                      //move left
     }

            swap(arr[leftBoundary], arr[rightBoundary]);


     while( pivot >= arr[leftBoundary]        //keep moving until a greater or equal element is found
            && leftBoundary < rightBoundary)      //or until the rightBoundary is reached
     {
          leftBoundary++;                        //move right
     }

            swap(arr[rightBoundary], arr[leftBoundary]);

}

return rightBoundary;                             //leftBoundary is the split point because
                                                  //the above while loop exits only when 
                                                  //leftBoundary and rightBoundary are equal
}

1 个答案:

答案 0 :(得分:1)

我认为算法中有一件事会导致问题。

更改行:

int pivot = arr[startIndex];

float pivot = arr[startIndex];

将float转换为int会截断小数,正如您正确设想的那样。这可能会解决您的问题。