Добавить task3.cpp
This commit is contained in:
70
task3.cpp
Normal file
70
task3.cpp
Normal file
@@ -0,0 +1,70 @@
|
|||||||
|
#include <iostream>
|
||||||
|
using namespace std;
|
||||||
|
|
||||||
|
void Pos(int* a, int n) {
|
||||||
|
int count = 0;
|
||||||
|
for (int i = 0; i < 3 && i < n; ++i)
|
||||||
|
if (a[i] > 0) ++count;
|
||||||
|
cout << "The number of the first 3 elements > 0: " << count << endl;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Show1(int* a, int n) {
|
||||||
|
cout << "The last 3 elements: ";
|
||||||
|
for (int i = (n >= 3 ? n - 3 : 0); i < n; ++i)
|
||||||
|
cout << a[i] << " ";
|
||||||
|
cout << endl;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Show2(int* a, int n) {
|
||||||
|
int* b = new int[n];
|
||||||
|
for (int i = 0; i < n; ++i) b[i] = a[i];
|
||||||
|
|
||||||
|
for (int i = 0; i < n-1; ++i)
|
||||||
|
for (int j = i+1; j < n; ++j)
|
||||||
|
if (b[i] > b[j]) { int t = b[i]; b[i] = b[j]; b[j] = t; }
|
||||||
|
cout << "The three smallest elements: ";
|
||||||
|
for (int i = 0; i < 3 && i < n; ++i) cout << b[i] << " ";
|
||||||
|
cout << endl;
|
||||||
|
delete[] b;
|
||||||
|
}
|
||||||
|
|
||||||
|
typedef void (*searchFunc)(int*, int);
|
||||||
|
|
||||||
|
void service(int* a, int n, searchFunc f) {
|
||||||
|
f(a, n);
|
||||||
|
}
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
srand(time(NULL));
|
||||||
|
int n;
|
||||||
|
cout << "n(n>=3)= ";
|
||||||
|
cin >> n;
|
||||||
|
if (n < 3) {
|
||||||
|
cerr << "Error: size Array!!";
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
int* arr = new int[n];
|
||||||
|
for (int i = 0; i < n; ++i)
|
||||||
|
arr[i] = rand() % 41 - 20;
|
||||||
|
|
||||||
|
cout << "Array: ";
|
||||||
|
for (int i = 0; i < n; ++i) cout << arr[i] << " ";
|
||||||
|
cout << endl;
|
||||||
|
|
||||||
|
searchFunc arrFunc[3] = { Pos, Show1, Show2 };
|
||||||
|
|
||||||
|
cout << "Menu:\n"
|
||||||
|
<< "1) The number of the first 3 elements > 0\n"
|
||||||
|
<< "2) Show the last 3 items\n"
|
||||||
|
<< "3) Display the 3 smallest elements\n"
|
||||||
|
<< "Select an action (1-3): ";
|
||||||
|
int choice;
|
||||||
|
cin >> choice;
|
||||||
|
if (choice >= 1 && choice <= 3)
|
||||||
|
service(arr, n, arrFunc[choice-1]);
|
||||||
|
else
|
||||||
|
cout << "Incorrect choice!\n";
|
||||||
|
|
||||||
|
delete[] arr;
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user