C/C++

Для массива а(к) найти наименьшее значение pазности между pядом стоящими эле-ментами.

#include <iostream>
#include <ctime>
#include <cmath>
using namespace std;
int main()
{
int k;
do
{
cout << "Введите k: ";
cin >> k;
}while(k < 2);
int * a = new int[k];
srand(time(nullptr));
rand();
for(int x = 0; x < k; x++)
{
a[x] = rand() % 11;
cout << a[x] << ' ';
}
cout << endl << endl;
int min = abs(a[1] - a[0]);
for(int x = 1; x < k - 1; x++)
{
if(abs(a[x+1] - a[x]) < min)
min = abs(a[x+1] - a[x]);
}
cout << "Наименьшее разности равно " << min << '.' << endl;
if(a != (int*) nullptr)
{
delete [] a;
a = (int*) nullptr;
}
return 1;
}
ЛА
Леман Аметов
92 918
Лучший ответ
#include <algorithm>
#include <iostream>
#include <random>
#include <iterator>
#include <numeric>
using namespace std;
int main() {
const auto min = 10;
const auto max = 99;
uniform_int_distribution<> uid(min, max);
mt19937 gen{ random_device()() };
auto rand = [&] { return uid(gen); };
const auto k = 10;
int a[k];
generate(begin(a), end(a), rand);
copy(begin(a), end(a), ostream_iterator<int>(cout, " "));
puts("");
auto difference = [](int a, int b) { return abs(a - b); };
int b[k];
adjacent_difference(begin(a), end(a), begin(b), difference);
auto target = *min_element(begin(b), end(b));
cout << target << '\n';
}
Владимир Попов
Владимир Попов
83 927
#include "iostream"
#include "iomanip"
#include "algorithm"
#include "ctime"
#include "cstdlib"
#include "cmath"
using namespace std;
int main(){
int n; cout<<"k: "; cin>>n; int *a=new int[n],*b=new int[n-1];
srand(time(NULL)); for(int i=0;i< n;i++)cout<< setw(4)<<(a[i]=rand()%199-99);
for(int i=1;i< n;i++)b[i-1]=abs(a[i]-a[i-1]);
cout<<"\n\nmin_diff="<<*min_element(b,b+n-1)<<'\n';}
Виталий Крячко
Виталий Крячко
86 686

Похожие вопросы