本帖最後由 李泳霖 於 2024-1-26 10:16 編輯
試運用 sort() 函式,搭配一個自定義的比較方法,對陣列做遞減排序。
![](https://seed.istak.org.tw/attachment.php?aid=MTYwMTV8ZWRhZjdjODd8MTY4ODYzNzY2M3xkMWM3WFFvRUJRWncyemZOZkxRdlJBQWtQMGJCcGw5VXF3MS8wdzVFVVJnWnlGZw%3D%3D&noupdate=yes) - #include<iostream>
- #include<cstdlib>
- #include<algorithm>
- using namespace std;
- bool compare(float a, float b)
- {
- return a>b;
- }
- int main()
- {
- float n[5]; //宣告一個大小為5的空陣列
- cout<<"請任意輸入5個浮點數:"<<endl;;
- for(int i=0; i<5; i++)
- cin>>n[i];
- cout<<"排序前:"<<endl;
- for(float f: n)
- cout<<f<<" ";
- cout<<endl;
- sort(n, n+5, compare);
- cout<<"排序後(遞減):"<<endl;
- for(float f: n)
- cout<<f<<" ";
- cout<<endl;
- system("pause");
- return 0;
- }
複製代碼 |