Re: [問題] C 指標與副程式問題

看板C_and_CPP作者 (pica)時間15年前 (2010/04/04 22:03), 編輯推噓0(0015)
留言15則, 3人參與, 最新討論串2/2 (看更多)
我把所有程式貼上來, ------------------------------------------------- 問題再簡述一次: step1 - Data 先由 PolyCalFun產生出來 step2 - 我讓 SortData = Data step3 - SortData 透過 SortFun 將數列從小到大排列 我讓一開始的數列 Data, 本來就是從小到大排列. 所以最後的結果, 應該不變: Data = [-125 -124.9 -124.8 ... 124.9 125]; SortData = [-125 -124.9 -124.8 ... 124.9 125]; -------------------------------------------------- /* Functionality : 輸入三個係數的二階多項式, 求出最大及最小值 Data : 2010/04/04 */ #include <cstdlib> #include <iostream> #include <cmath> #define DimX (250*10+1) #define interval 0.1 void PolyCalFun(float*, float, float, float); void SortFun(float*); using namespace std; int main(int argc, char *argv[]) { float Data[DimX]={0}; float SortData[DimX]={0}; float a=0, b=1, c=0; // 二階多項式的三個參數 a, b, c cout<< endl <<"輸入多項式的三個參數 y = ax^2+ bx + c"<< endl<<endl; // 計算多項式的值, cout<< endl <<" // 計算從 x = -125:0.1:125, 的多項式值 " << endl; PolyCalFun(&Data[0], a, b, c); // 複製資料 for(int i=0; i<DimX; ++i) { SortData[i] = Data[i]; } // 排序 SortFun(&SortData[0]); for(int i=0; i<DimX; ++i) { cout<<Data[i]<<" "; cout<<SortData[i]<<" "; system("pause"); } // 最大值輸出 cout <<endl << "最大值 " <<endl; cout << SortData[DimX-1]<<endl; cout <<endl << "最小值 " <<endl; cout << SortData[0]<<endl; system("PAUSE"); return EXIT_SUCCESS; } void SortFun(float* SortData) { float temp; // 從小到大排列 for (int i=0; i<DimX; ++i) { for (int SearchRange = i+1; SearchRange<DimX; ++SearchRange) { if (SortData[i]>SortData[i+SearchRange]) { temp = SortData[i+SearchRange]; SortData[i+SearchRange] = SortData[i]; SortData[i] = temp; } } } } void PolyCalFun(float* data, float a, float b, float c) { double valX = -125; // 計算從 x = -125:0.1:125, 的多項式值 int i; for ( i=0; i<DimX; ++i) { data[i] = a*(valX*valX)+ b*(valX) + c; valX = valX+interval; } } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 60.198.94.135 ※ 編輯: einstein328 來自: 60.198.94.135 (04/04 22:20)

04/04 22:12, , 1F
不知道是不是因為在同一個loop同時印Data和SortData
04/04 22:12, 1F

04/04 22:12, , 2F
造成的誤會
04/04 22:12, 2F

04/04 22:22, , 3F
不行阿, 我試過讓Data 和 SortData 個別秀出來,還是錯
04/04 22:22, 3F
※ 編輯: einstein328 來自: 60.198.94.135 (04/04 22:45)

04/04 22:52, , 4F
感覺你這行 if (SortData[i]>SortData[i+SearchRange])
04/04 22:52, 4F

04/04 22:54, , 5F
怪怪的耶~ 是想做slection sort吧?
04/04 22:54, 5F

04/04 22:57, , 6F
對阿, 找出 SortData[i]的最小值
04/04 22:57, 6F

04/04 23:01, , 7F
即使SortFun有問題, 也不會影響Data吧, 這就是我覺得
04/04 23:01, 7F

04/04 23:02, , 8F
奇怪的地方
04/04 23:02, 8F

04/04 23:02, , 9F
if (SortData[i]>SortData[SearchRange]) <-這樣呢?
04/04 23:02, 9F

04/04 23:03, , 10F
感覺就是Buffer overflow
04/04 23:03, 10F

04/04 23:04, , 11F
我想問題不是出現在SortFun上
04/04 23:04, 11F

04/04 23:06, , 12F
其實也是有可能... 寫到下個變數的內容
04/04 23:06, 12F

04/04 23:08, , 13F
真的ㄟ
04/04 23:08, 13F

04/04 23:09, , 14F
太感謝了, 我錯了, 的確會影響, 感謝, 我搞好久
04/04 23:09, 14F

04/04 23:11, , 15F
科科科科
04/04 23:11, 15F
文章代碼(AID): #1Bk9nFRH (C_and_CPP)
文章代碼(AID): #1Bk9nFRH (C_and_CPP)