gpt4 book ai didi

c++ - OpenMP 截断 float

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:10:11 24 4
gpt4 key购买 nike

我正在从 CSV 文件中读取数据 (一维/vector )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
}

最佳答案

我认为您的算法中有一件事导致了问题。

换行:

int pivot = arr[startIndex];

float pivot = arr[startIndex];

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

关于c++ - OpenMP 截断 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43025028/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com