数组中相差最小的两个元素(最接近数)的差

设计算法数组中相差最小的两个元素(称为最接近数)的差。

//设计算法数组中相差最小的两个元素(称为最接近数)的差。
#include<iostream>
using namespace std;
#define N 20
void test(int len, int a[]);
int main()
{
    
    
	int len;

	cout << "输入数组的长度len:";
	cin >> len;
	int a[N];
	for (int i = 0; i < len; i++) {
    
    
		cout << "输入元素a[" << i << "]=";
		cin >> a[i];
	}
	test(len, a);
	return 0;
}

void test(int len,int a[] ) {
    
    
	int x = abs(a[1] - a[2]);
	for (int i = 0; i < len; i++) {
    
    
		for (int j = i + 1; j < len; j++) {
    
    
			int k = abs(a[i] - a[j]);
			if (k <= x) {
    
    
				x = k;
			}
		}
	}
	cout << "相差最小的两个元素的差是:" << x << endl;
}

猜你喜欢

转载自blog.csdn.net/qq_45784099/article/details/114436707
今日推荐