【水】HDU2020 絕對值排序
阿新 • • 發佈:2018-12-11
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) [顯示標籤] Description 輸入n(n<=100)個整數,按照絕對值從大到小排序後輸出。題目保證對於每一個測試例項,所有的數的絕對值都不相等。 Input 輸入資料有多組,每組佔一行,每行的第一個數字為n,接著是n個整數,n=0表示輸入資料的結束,不做處理。 Output 對於每個測試例項,輸出排序後的結果,兩個數之間用一個空格隔開。每個測試例項佔一行。 Sample Input 3 3 -4 2 4 0 1 2 -3 0 Sample Output -4 3 2 -3 2 1 0 Hint lcy Source C語言程式設計練習(三) Related problem 2015 2016 2018 2023 2024
仿造氣泡排序法,然後比較部分記得加絕對值演算法fabs().輸出格式注意一下就好了。
程式碼如下:
#include <iostream> #include <cmath> using namespace std; int main() { int n,a[100]; while(cin >> n, n!=0) { for(int i=0;i<n;i++) cin>>a[i]; for(int i=0;i<n;i++) for(int j=0;j<n-1-i;j++) if(fabs(a[j])<fabs(a[j+1])) { int temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; } for(int i=0;i<n;i++) { cout<<a[i]; if(i<n) cout<<" "; else cout<<endl; } } }