C/C++编程学习 - 第11周 ⑥ 绝对值排序

题目链接

题目描述

输入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

思路

题意是按照绝对值从大到小排序后输出。传统的sort是默认从小到大排序的,因此我们可以写一个cmp函数,按照绝对值从大到小排序后输出。

具体怎么写cmp函数呢?请看代码:

C++代码:

#include<bits/stdc++.h>
using namespace std;
int num[105];
int cmp(int a, int b)
{
    
    
	return abs(a) > abs(b);
}
int main()
{
    
    
	int n;
	while(cin >> n)
	{
    
    
		if(n == 0) break;
		for(int i = 0; i < n; i++)
			cin >> num[i];
		sort(num, num + n, cmp);
		for(int i = 0; i < n; i++)
			i == 0 ? cout << num[i] : cout << " " << num[i];
		cout << endl;
	}
	return 0;
}

abs()函数就是求绝对值函数了,cmp函数中的大于号">“表示是从大到小排序的,如果想改为从小到大排序,则需要写小于号”<"。

猜你喜欢

转载自blog.csdn.net/qq_44826711/article/details/113100189
今日推荐