Работы по программированию

This commit is contained in:
IgorVolochay
2026-07-28 09:56:54 +03:00
parent b85155ff95
commit 8602b7e845
73 changed files with 4090 additions and 0 deletions
+12
View File
@@ -0,0 +1,12 @@
{
"files.associations": {
"cstdlib": "c",
"math.h": "c",
"ostream": "cpp",
"iosfwd": "cpp",
"algorithm": "cpp",
"iterator": "cpp",
"xmemory": "cpp",
"xutility": "cpp"
}
}
+28
View File
@@ -0,0 +1,28 @@
{
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: gcc.exe build active file",
"command": "D:\\mingw\\MinGW\\bin\\gcc.exe",
"args": [
"-fdiagnostics-color=always",
"-g",
"${file}",
"-o",
"${fileDirname}\\${fileBasenameNoExtension}.exe"
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "Task generated by Debugger."
}
],
"version": "2.0.0"
}
+17
View File
@@ -0,0 +1,17 @@
/*
1.Даны целочисленные переменные А и В. Найти их сумму и вывести на экран.
*/
#include <stdio.h>
int getSum(int a, int b) {
return a + b;
}
int main() {
const int A = 3;
const int B = 8;
printf("Sum: %d", getSum(A, B));
return 0;
}
+38
View File
@@ -0,0 +1,38 @@
/*
10.Создать целочисленный массив A[5][5]. При помощи цикла и оператора условия задать его значения, как показано ниже:
1 2 3 4 5
2 3 4 5 4
3 4 5 4 3
4 5 4 3 2
5 4 3 2 1
*/
#include <stdio.h>
#define N 5
void setArray(int (*array)[N]) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
array[i][j] = (i + j) < (N-1) ? i + j + 1 : (N*2 - 1) - (i+j);
}
}
}
void printArray(int (*array)[N] ) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
printf("%d ", array[i][j]);
}
puts("");
}
}
int main() {
int A[N][N];
setArray(A);
printArray(A);
return 0;
}
+69
View File
@@ -0,0 +1,69 @@
/*
11.На поле 10х10 клеток установить 10 однопалубных кораблей. Корабли не соприкасаются.
*/
#include <stdio.h>
#include <stdbool.h>
#include <time.h>
#include <stdlib.h>
#include <math.h>
#define N 10
#define AMOUNT 10
const char SHIP = '#';
const char VOID = '.';
char matrix[N][N];
void fillMatrix() {
for (int i=0;i<N;i++) {
for (int j=0;j<N;j++) {
matrix[i][j] = VOID;
}
}
}
void printMatrix() {
for (int i=0;i<N;i++) {
for (int j=0;j<N;j++) {
printf("%2c", matrix[i][j]);
}
puts("");
}
}
bool isCanPlace(int x, int y) {
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1;j++) {
if (matrix[abs(x-i)][abs(y-j)] == SHIP)
return false;
}
}
return true;
}
void setShips() {
for (int i = 0; i < AMOUNT; i++) {
int x = rand() % N;
int y = rand() % N;
if (isCanPlace(x, y)) {
matrix[x][y] = SHIP;
} else {
i--;
}
}
}
int main() {
srand(time(0));
fillMatrix();
setShips();
printMatrix();
return 0;
}
+74
View File
@@ -0,0 +1,74 @@
/*
12.На поле 10х10 клеток установить 5 двухпалубных кораблей. Корабли не соприкасаются.
*/
#include <stdio.h>
#include <stdbool.h>
#include <time.h>
#include <stdlib.h>
#include <math.h>
#define N 10
#define AMOUNT 5
const char SHIP = '#';
const char VOID = '.';
char matrix[N][N];
void fillMatrix() {
for (int i=0;i<N;i++) {
for (int j=0;j<N;j++) {
matrix[i][j] = VOID;
}
}
}
void printMatrix() {
for (int i=0;i<N;i++) {
for (int j=0;j<N;j++) {
printf("%2c", matrix[i][j]);
}
puts("");
}
}
bool isCanPlace(int x, int y) {
for (int i = -2; i <= 2; i++) {
for (int j = -2; j <= 2;j++) {
if (matrix[abs(x-i)][abs(y-j)] == SHIP)
return false;
}
}
return true;
}
void setShips() {
for (int i = 0; i < AMOUNT; i++) {
int x = rand() % (N - 1);
int y = rand() % (N - 1);
if (isCanPlace(x, y)) {
matrix[x][y] = SHIP;
if (rand() % 2 == 0) {
matrix[x+1][y] = SHIP;
} else {
matrix[x][y+1] = SHIP;
}
} else {
i--;
}
}
}
int main() {
srand(time(0));
fillMatrix();
setShips();
printMatrix();
return 0;
}
+55
View File
@@ -0,0 +1,55 @@
/*
13.Написать программу, которая шифрует и дешифрует сообщение Шифром Цезаря.
*/
#include <stdio.h>
#include <string.h>
#define OFFSET 13
char* encrypt(char* string) {
char *result = string;
for (int i =0; i < strlen(string);i++) {
char c = string[i];
if (c >= 'A' && c <= 'Z') {
c = c + (OFFSET % 26);
if (c > 'Z') c = 'A' + (c - 'Z') - 1;
}
if (c >= 'a' && c <= 'z') {
c = c + (OFFSET % 26);
if (c > 'z') c= 'a' + (c - 'z') - 1;
}
result[i] = c;
}
return result;
}
char* decrypt(char* string) {
char *result = string;
for (int i =0; i < strlen(string);i++) {
char c = string[i];
if (c >= 'A' && c <= 'Z') {
c = c - (OFFSET % 26);
if (c < 'A') c = 'Z' - ('A' - c) + 1;
}
if (c >= 'a' && c <= 'z') {
c = c - (OFFSET % 26);
if (c < 'a') c= 'z' - ('a' - c) + 1;
}
result[i] = c;
}
return result;
}
int main() {
char string[32];
scanf("%s", string);
char *enc = encrypt(string);
printf("%s\n", enc);
printf("%s", decrypt(enc));
return 0;
}
+60
View File
@@ -0,0 +1,60 @@
/*
15.Вычислить сумму двух обыкновенных дробей. Ответ дать в виде обыкновенной и в виде десятичной дробей. Числители и знаменатели относятся к целому типу данных.
*/
#include <stdio.h>
#include <math.h>
typedef struct Fraction {
int up;
int down;
} fraction;
int GCD(int a, int b) {
int result = (a < b) ? a : b;
while (result > 0)
{
if (a % result == 0 && b % result == 0)
{
break;
}
result--;
}
return result;
}
int LCM(int a, int b) {
return a / GCD(a, b) * b;
}
void printSumFraction(fraction fraction_1, fraction fraction_2) {
int a = fraction_1.up;
int b = fraction_1.down;
int c = fraction_2.up;
int d = fraction_2.down;
/*
a c
- + -
b d
*/
int lcm = LCM(b, d);
int answer_up = a * (lcm / b) + c * (lcm / d);
printf("%2d %2d %2d * %2d + %2d %2d\n", a, c, a, lcm / b, c*lcm / d, a * (lcm / b) + c * (lcm / d));
printf("-- + -- = ------------ = -- = %.3lf\n", (double)answer_up/lcm);
printf("%2d %2d %2d %2d\n", b, d, lcm, lcm);
}
int main()
{
fraction first;
fraction second;
printf("Enter a b c and d: ");
scanf("%d %d %d %d", &first.up, &first.down, &second.up, &second.down);
printSumFraction(first, second);
return 0;
}
+63
View File
@@ -0,0 +1,63 @@
/*
16.Вычислить разность двух обыкновенных дробей. Ответ дать в виде обыкновенной и в виде десятичной дробей. Числители и знаменатели относятся к целому типу данных.*/
#include <stdio.h>
#include <math.h>
typedef struct Fraction
{
int up;
int down;
} fraction;
int GCD(int a, int b)
{
int result = (a < b) ? a : b;
while (result > 0)
{
if (a % result == 0 && b % result == 0)
{
break;
}
result--;
}
return result;
}
int LCM(int a, int b)
{
return a / GCD(a, b) * b;
}
void printSumFraction(fraction fraction_1, fraction fraction_2)
{
int a = fraction_1.up;
int b = fraction_1.down;
int c = fraction_2.up;
int d = fraction_2.down;
/*
a c
- - -
b d
*/
int lcm = LCM(b, d);
int answer_up = a * (lcm / b) - c * (lcm / d);
printf("%2d %2d %2d * %2d - %2d %2d\n", a, c, a, lcm / b, c * lcm / d, a * (lcm / b) - c * (lcm / d));
printf("-- - -- = ------------ = -- = %.3lf\n", (double)answer_up / lcm);
printf("%2d %2d %2d %2d\n", b, d, lcm, lcm);
}
int main()
{
fraction first;
fraction second;
printf("Enter a b c and d: ");
scanf("%d %d %d %d", &first.up, &first.down, &second.up, &second.down);
printSumFraction(first, second);
return 0;
}
+42
View File
@@ -0,0 +1,42 @@
/*
17.Вычислить произведение двух обыкновенных дробей. Ответ дать в виде обыкновенной и в виде десятичной дробей. Числители и знаменатели относятся к целому типу данных.
*/
#include <stdio.h>
#include <math.h>
typedef struct Fraction
{
int up;
int down;
} fraction;
void printSumFraction(fraction fraction_1, fraction fraction_2)
{
int a = fraction_1.up;
int b = fraction_1.down;
int c = fraction_2.up;
int d = fraction_2.down;
/*
a c
- * -
b d
*/
printf("%2d %2d %2d * %2d %2d\n", a, c, a, c, a*c);
printf("-- * -- = ------------ = -- = %.3lf\n", (double)(a*c)/(b*d));
printf("%2d %2d %2d * %2d %2d\n", b, d, b,d, b*d);
}
int main()
{
fraction first;
fraction second;
printf("Enter a b c and d: ");
scanf("%d %d %d %d", &first.up, &first.down, &second.up, &second.down);
printSumFraction(first, second);
return 0;
}
+42
View File
@@ -0,0 +1,42 @@
/*
18.Вычислить частное двух обыкновенных дробей. Ответ дать в виде обыкновенной и в виде десятичной дробей. Числители и знаменатели относятся к целому типу данных.
*/
#include <stdio.h>
#include <math.h>
typedef struct Fraction {
int up;
int down;
} fraction;
void printSumFraction(fraction fraction_1, fraction fraction_2) {
int a = fraction_1.up;
int b = fraction_1.down;
int c = fraction_2.up;
int d = fraction_2.down;
/*
a c
- : -
b d
*/
printf("%2d %2d %2d * %2d %2d * %2d %2d\n", a, c, a, d, a, d, a * d);
printf("-- : -- = --- --- = ------- = -- = %.3lf\n", (double)(a * d) / (b * c));
printf("%2d %2d %2d * %2d %2d * %2d %2d\n", b, d, b, c, b, c, b * c);
}
int main()
{
fraction first;
fraction second;
printf("Enter a b c and d: ");
scanf("%d %d %d %d", &first.up, &first.down, &second.up, &second.down);
printSumFraction(first, second);
return 0;
}
+22
View File
@@ -0,0 +1,22 @@
/*
19.Вычислить определитель матрицы 3x3.
*/
#include <stdio.h>
#define N 3
int getDet(int (*matrix)[N]) {
return matrix[0][0]*matrix[1][1]*matrix[2][2] + matrix[0][1]*matrix[1][2]*matrix[2][0] + matrix[0][2]*matrix[1][0]*matrix[2][1] - matrix[0][2]*matrix[1][1]*matrix[2][0] - matrix[0][1]*matrix[1][0]*matrix[2][2] - matrix[0][0]*matrix[1][2]*matrix[2][1];
}
int main() {
int matrix[N][N] = {{6, 3, 0},
{4, 1, -3},
{-2, -3, 2}
};
printf("Det: %d", getDet(matrix));
return 0;
}
+17
View File
@@ -0,0 +1,17 @@
/*
2.Даны целочисленные переменные А и В. Найти их частное, вывести на экран с точностью до двух знаков после запятой.
*/
#include <stdio.h>
double getDivision(double a, double b) {
return a/b;
}
int main() {
const int A = 10;
const int B = 4;
printf("%.2lf", getDivision(A, B));
return 0;
}
+66
View File
@@ -0,0 +1,66 @@
/*
20.Вычислить корни СЛАУ через определители
*/
#include <stdio.h>
#include <string.h>
#define N 3
#define M 4
int getDet(int (*matrix)[N])
{
return matrix[0][0] * matrix[1][1] * matrix[2][2] + matrix[0][1] * matrix[1][2] * matrix[2][0] + matrix[0][2] * matrix[1][0] * matrix[2][1] - matrix[0][2] * matrix[1][1] * matrix[2][0] - matrix[0][1] * matrix[1][0] * matrix[2][2] - matrix[0][0] * matrix[1][2] * matrix[2][1];
}
void setMatrixNew(int (*matrix_new)[N], int (*matrix)[M])
{
for (int x = 0; x < N; x++)
{
for (int y = 0; y < N; y++)
{
matrix_new[x][y] = matrix[x][y];
}
}
}
int getSolve(int (*matrix)[M])
{
int matrix_new[N][N];
setMatrixNew(matrix_new, matrix);
int X = getDet(matrix_new);
if (X == 0) {
puts("KOD KRASBYI!!");
return;
}
int x_array[N];
for (int i = N - 1; i >= 0; i--)
{
setMatrixNew(matrix_new, matrix);
matrix_new[0][i] = matrix[0][M - 1];
matrix_new[1][i] = matrix[1][M - 1];
matrix_new[2][i] = matrix[2][M - 1];
x_array[i] = getDet(matrix_new);
printf("%d\n", getDet(matrix_new));
}
char current = 'x';
for (int i = 0; i < N;i++) {
printf("%c = %.2lf\n", current++, (double)x_array[i]/X);
}
}
int main()
{
int matrix[N][M] = {{1, 2, 3, 3},
{3, 2, 2, 3},
{3, 3, 3, 3}};
getSolve(matrix);
return 0;
}
+67
View File
@@ -0,0 +1,67 @@
/*
21.Выполнить сортировку одномерного массива A[25] методом пузырька.
*/
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <stdbool.h>
#define N 25
void initArray(int *array, const int MAX)
{
srand(time(0));
for (int i = 0; i < N; i++)
{
array[i] = rand() % MAX + 1;
}
}
void _swap(int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
void sortArrayBubble(int *array)
{
int i, j;
bool is_swap;
for (i = 0; i < N - 1; i++)
{
is_swap = false;
for (j = 0; j < N - i - 1; j++)
{
if (array[j] > array[j + 1])
{
_swap(&array[j], &array[j + 1]);
is_swap = true;
}
}
if (is_swap == false)
break;
}
}
void printArray(int *array)
{
for (int i = 0; i < N; i++)
{
printf("%d ", array[i]);
}
}
int main()
{
int A[N];
initArray(A, 10);
sortArrayBubble(A);
printArray(A);
return 0;
}
+79
View File
@@ -0,0 +1,79 @@
/*
22.Выполнить сортировку одномерного массива A[25] методом быстрой сортировки.
*/
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <stdbool.h>
#define N 25
void initArray(int *array, const int MAX)
{
srand(time(0));
for (int i = 0; i < N; i++)
{
array[i] = rand() % MAX + 1;
}
}
void sortArrayQuick(int *array, int size)
{
int i = 0;
int j = size - 1;
int middle = array[size / 2];
do
{
while (array[i] < middle)
{
i++;
}
while (array[j] > middle)
{
j--;
}
if (i <= j)
{
int tmp = array[i];
array[i] = array[j];
array[j] = tmp;
i++;
j--;
}
} while (i <= j);
if (j > 0)
{
sortArrayQuick(array, j + 1);
}
if (i < size)
{
sortArrayQuick(&array[i], size - i);
}
}
void printArray(int *array)
{
for (int i = 0; i < N; i++)
{
printf("%d ", array[i]);
}
}
int main()
{
int A[N];
initArray(A, 10);
sortArrayQuick(A, N);
printArray(A);
return 0;
}
+64
View File
@@ -0,0 +1,64 @@
/*
23.Выполнить сортировку одномерного массива A[25] методом сортировки вставкой.
*/
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <stdbool.h>
#define N 25
void initArray(int *array, const int MAX)
{
srand(time(0));
for (int i = 0; i < N; i++)
{
array[i] = rand() % MAX + 1;
}
}
void _swap(int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
void sortArrayInsertion(int *array)
{
int i, key, j;
for (i = 1; i < N; i++)
{
key = array[i];
j = i - 1;
while (j >= 0 && array[j] > key)
{
array[j + 1] = array[j];
j = j - 1;
}
array[j + 1] = key;
}
}
void printArray(int *array)
{
for (int i = 0; i < N; i++)
{
printf("%d ", array[i]);
}
}
int main()
{
int A[N];
initArray(A, 10);
sortArrayInsertion(A);
printArray(A);
return 0;
}
+85
View File
@@ -0,0 +1,85 @@
/*
24.В функции main есть два массива: A[5] и B[10].
Написать две функции – одна сортирует массивы по возрастанию (один массив за один вызов функции),
а другая – выводит значения элементов массива (один массив за один вызов функции).
Массивы в функции main находятся в одной области памяти, отсортированные – в другой.
После вызова функции вывести результат сортировки и исходные массивы.
Сами исходные массивы в функции main остаются без изменений.
*/
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define SIZE_A 5
#define SIZE_B 10
void initArray(int *array, int size, const int MAX)
{
srand(time(0));
for (int i = 0; i < size; i++)
{
array[i] = rand() % MAX + 1;
}
}
void sortArrayInsertion(int *array, int size)
{
int i, key, j;
for (i = 1; i < size; i++)
{
key = array[i];
j = i - 1;
while (j >= 0 && array[j] > key)
{
array[j + 1] = array[j];
j = j - 1;
}
array[j + 1] = key;
}
}
void printArray(int *array, int size)
{
for (int i = 0; i < size; i++)
{
printf("%d ", array[i]);
}
puts("");
}
int main()
{
int A[SIZE_A];
int B[SIZE_B];
initArray(A, SIZE_A, 10);
initArray(B, SIZE_B, 15);
int A_sort[SIZE_A];
int B_sort[SIZE_B];
memcpy(A_sort, A, sizeof(A));
memcpy(B_sort, B, sizeof(B));
sortArrayInsertion(A_sort, SIZE_A);
sortArrayInsertion(B_sort, SIZE_B);
printf("A[%d] = ", SIZE_A);
printArray(A, SIZE_A);
printf("Sorted A[%d] = ", SIZE_A);
printArray(A_sort, SIZE_A);
printf("B[%d] = ", SIZE_A);
printArray(B, SIZE_B);
printf("Sorted B[%d] = ", SIZE_A);
printArray(B_sort, SIZE_B);
return 0;
}
+40
View File
@@ -0,0 +1,40 @@
/*
25. Выполнить подготовку для рисования графика функции y=sin(x), x [-2pi;2pi].
С шагом pi/180. Значения (x,y) записать в файл «sinraw.txt», как есть
*/
#include <stdio.h>
#include <math.h>
#define M_PI 3.14159265358979323846
void writeXY()
{
FILE *file = fopen("sinraw.txt", "w");
if (file == NULL)
{
printf("Error open\n");
return;
}
double a = 0;
double b = 2 * M_PI;
double h = 0.1;
for (double x = a; x <= b; x += h)
{
double y = sin(x);
fprintf(file, "%f %f\n", x, y);
}
fclose(file);
}
int main()
{
writeXY();
return 0;
}
+48
View File
@@ -0,0 +1,48 @@
/*
26.Аналогично заданию 25, но в файл «singood.txt» записать экранные координаты (x,y).
Для этого следует учесть:
* масштабирование по оси ОХ = 50, по оси ОУ = 40
* начало экранных координат установлено в точке (320, 240)
*/
#include <stdio.h>
#include <math.h>
#define M_PI 3.14159265358979323846
void writeXY()
{
FILE *file = fopen("singood.txt", "w");
if (file == NULL)
{
printf("Error open\n");
return;
}
double a = 0;
double b = 2 * M_PI;
double h = 0.1;
double scale_x = 50;
double scale_y = 40;
double offset_x = 320;
double offset_y = 240;
for (double x = a; x <= b; x += h)
{
double y = sin(x);
fprintf(file, "%f %f\n", x, y);
double x_screen = x * scale_x + offset_x;
double y_screen = -y * scale_y + offset_y;
fprintf(file, "%f %f\n", x_screen, y_screen);
}
fclose(file);
}
int main()
{
writeXY();
return 0;
}
+53
View File
@@ -0,0 +1,53 @@
/*
29.Загадать случайным образом 100 чисел в диапазоне [-50;75].
Записать их в файл «binint.dat» - каждое число записывается в файл в 4-х байтном представлении.
Прочитать данные из файла «binint.dat», найти сумму чисел в нём.
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
const int MIN = -50;
const int MAX = 75;
const int AMOUNT = 100;
int* getRandomArray() {
srand(time(0));
int *array = malloc(sizeof(int)*AMOUNT);
for (int i = 0; i < AMOUNT;i++) {
array[i] = rand() % (abs(MIN) + abs(MAX) + 1) - abs(MIN);
}
return array;
}
void writeData(char* filename) {
FILE *file = fopen(filename, "wb");
int *array = getRandomArray();
for (int i = 0; i < AMOUNT; i++) {
fwrite(&array[i], sizeof(int), 1, file);
}
fclose(file);
}
int getSummaryNumbers(char* filename) {
FILE *file = fopen(filename, "rb");
int number, summary = 0;
while(fread(&number, sizeof(int), 1, file) == 1) {
summary += number;
}
fclose(file);
return summary;
}
int main() {
char *filename = "binint.dat";
writeData(filename);
printf("Summary: %d", getSummaryNumbers(filename));
return 0;
}
+44
View File
@@ -0,0 +1,44 @@
/*
3.Даны целочисленные переменные А, В и С. Задать их вводом с клавиатуры. Вывести в порядке возрастания. (только оператор условия)
*/
#include <stdio.h>
#include <stdlib.h>
int* getNumbers(int a, int b, int c) {
if (a > b) {
int tmp = a;
a = b;
b = tmp;
}
if (b > c) {
int tmp = b;
b = c;
c = tmp;
}
if (a > b) {
int tmp = a;
a = b;
b = tmp;
}
int *answer = malloc(sizeof(int) * 3);
answer[0] = a;
answer[1] = b;
answer[2] = c;
return answer;
}
int main() {
int a, b, c;
printf("Enter 3 numbers: ");
scanf("%d %d %d", &a, &b, &c);
int *result = getNumbers(a, b ,c);
printf("Sorted: %d %d %d", result[0], result[1], result[2]);
free(result);
return 0;
}
+53
View File
@@ -0,0 +1,53 @@
/*
30.Загадать случайным образом 50 действительных чисел в диапазоне [-5.5;5.5].
Записать их в файл «binfloat.dat» - каждое число записывается в 4-х байтном представлении.
Прочитать данные из файла «binfloat.dat», найти максимальное значение.
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
const int MIN = -55;
const int MAX = 55;
const int AMOUNT = 50;
float* getRandomFloatArray() {
srand(time(0));
float *array = malloc(sizeof(float)*AMOUNT);
for (int i = 0; i < AMOUNT;i++) {
array[i] = (rand() % (abs(MIN) + abs(MAX) + 1) - abs(MIN))/10.0f;
}
return array;
}
void writeData(char* filename) {
FILE *file = fopen(filename, "wb");
float *array = getRandomFloatArray();
for (int i = 0; i < AMOUNT; i++) {
fwrite(&array[i], sizeof(float), 1, file);
}
fclose(file);
}
float getMaximumNumber(char* filename) {
FILE *file = fopen(filename, "rb");
float number, maximum = 0;
while(fread(&number, sizeof(float), 1, file) == 1) {
maximum = maximum < number ? number : maximum;
}
fclose(file);
return maximum;
}
int main() {
char *filename = "binfloat.dat";
writeData(filename);
printf("Maximum: %.1f", getMaximumNumber(filename));
return 0;
}
+24
View File
@@ -0,0 +1,24 @@
/*
4.Даны целочисленные переменные А и В. Задать их значения с клавиатуры. Поменять значения в переменных А и В без дополнительных переменных.
*/
#include <stdio.h>
void swap(int *a, int *b) {
*a += *b;
*b = *a - *b;
*a -= *b;
}
int main() {
int a, b;
printf("Enter 2 digits: ");
scanf("%d %d", &a, &b);
swap(&a, &b);
printf("%d %d", a ,b);
return 0;
}
+35
View File
@@ -0,0 +1,35 @@
/*
5.Дана переменная А. Задать ее значение с клавиатуры (от 1 до 7). Используя оператор SWITCH…CASE вывести на экран соответствующий день недели.
*/
#include <stdio.h>
char* getDay(int number) {
switch (number) {
case 1:
return "Monday";
case 2:
return "Tuesday";
case 3:
return "Wednesday";
case 4:
return "Thursday";
case 5:
return "Friday";
case 6:
return "Saturday";
case 7:
return "Sunday";
default:
return "number not between 1..7";
}
}
int main() {
int number;
printf("Enter number day: ");
scanf("%d", &number);
printf("Answer: %s", getDay(number));
return 0;
}
+25
View File
@@ -0,0 +1,25 @@
/*
6.Создать структуру, содержащую два поля – NAME и AGE. Задать две переменные типа этой структуры. Ввести их значения с клавиатуры и вывести на экран.
*/
#include <stdio.h>
struct person {
char NAME[32];
int AGE;
};
int main() {
struct person p1, p2;
printf("Enter name and age first person: ");
scanf("%s %d", p1.NAME, &p1.AGE);
printf("Enter name and age second person: ");
scanf("%s %d", p2.NAME, &p2.AGE);
printf("First person: %s, %2d age\n", p1.NAME, p1.AGE);
printf("Second person: %s, %2d age\n", p2.NAME, p2.AGE);
return 0;
}
+38
View File
@@ -0,0 +1,38 @@
/*
7.Создать целочисленный массив A[5][5]. При помощи цикла и оператора условия задать его значения, как показано ниже:
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4
5 5 5 5 5
*/
#include <stdio.h>
#define N 5
void setArray(int (*array)[N]) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
array[i][j] = i+1;
}
}
}
void printArray(int (*array)[N] ) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
printf("%2d", array[i][j]);
}
puts("");
}
}
int main() {
int A[N][N];
setArray(A);
printArray(A);
return 0;
}
+38
View File
@@ -0,0 +1,38 @@
/*
8.Создать целочисленный массив A[5][5]. При помощи цикла и оператора условия задать его значения, как показано ниже:
5 5 5 5 5
4 4 4 4 4
3 3 3 3 3
2 2 2 2 2
1 1 1 1 1
*/
#include <stdio.h>
#define N 5
void setArray(int (*array)[N]) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
array[i][j] = N - i;
}
}
}
void printArray(int (*array)[N] ) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
printf("%2d", array[i][j]);
}
puts("");
}
}
int main() {
int A[N][N];
setArray(A);
printArray(A);
return 0;
}
+44
View File
@@ -0,0 +1,44 @@
/*
9.Создать целочисленный массив A[5][5]. При помощи цикла и оператора условия задать его значения, как показано ниже:
5 4 3 2 1
4 3 2 1 2
3 2 1 2 3
2 1 2 3 4
1 2 3 4 5
*/
#include <stdio.h>
#define N 5
void setArray(int (*array)[N]) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
int result;
if ( i+j < N) {
result = N - (i+j);
} else {
result = (i+j) - (N - 2);
}
array[i][j] = result;
}
}
}
void printArray(int (*array)[N] ) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
printf("%d ", array[i][j]);
}
puts("");
}
}
int main() {
int A[N][N];
setArray(A);
printArray(A);
return 0;
}
Binary file not shown.
Binary file not shown.
+362
View File
@@ -0,0 +1,362 @@
// The winbgim library, Version 6.0, August 9, 2004
// Written by:
// Grant Macklem (Grant.Macklem@colorado.edu)
// Gregory Schmelter (Gregory.Schmelter@colorado.edu)
// Alan Schmidt (Alan.Schmidt@colorado.edu)
// Ivan Stashak (Ivan.Stashak@colorado.edu)
// Michael Main (Michael.Main@colorado.edu)
// CSCI 4830/7818: API Programming
// University of Colorado at Boulder, Spring 2003
// ---------------------------------------------------------------------------
// Notes
// ---------------------------------------------------------------------------
// * This library is still under development.
// * Please see http://www.cs.colorado.edu/~main/bgi for information on
// * using this library with the mingw32 g++ compiler.
// * This library only works with Windows API level 4.0 and higher (Windows 95, NT 4.0 and newer)
// * This library may not be compatible with 64-bit versions of Windows
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// Macro Guard and Include Directives
// ---------------------------------------------------------------------------
#ifndef WINBGI_H
#define WINBGI_H
#include <windows.h> // Provides the mouse message types
#include <limits.h> // Provides INT_MAX
#include <sstream> // Provides std::ostringstream
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// Definitions
// ---------------------------------------------------------------------------
// Definitions for the key pad extended keys are added here. When one
// of these keys are pressed, getch will return a zero followed by one
// of these values. This is the same way that it works in conio for
// dos applications.
#define KEY_HOME 71
#define KEY_UP 72
#define KEY_PGUP 73
#define KEY_LEFT 75
#define KEY_CENTER 76
#define KEY_RIGHT 77
#define KEY_END 79
#define KEY_DOWN 80
#define KEY_PGDN 81
#define KEY_INSERT 82
#define KEY_DELETE 83
#define KEY_F1 59
#define KEY_F2 60
#define KEY_F3 61
#define KEY_F4 62
#define KEY_F5 63
#define KEY_F6 64
#define KEY_F7 65
#define KEY_F8 66
#define KEY_F9 67
// Line thickness settings
#define NORM_WIDTH 1
#define THICK_WIDTH 3
// Character Size and Direction
#define USER_CHAR_SIZE 0
#define HORIZ_DIR 0
#define VERT_DIR 1
// Constants for closegraph
#define CURRENT_WINDOW -1
#define ALL_WINDOWS -2
#define NO_CURRENT_WINDOW -3
// The standard Borland 16 colors
#define MAXCOLORS 15
enum colors { BLACK, BLUE, GREEN, CYAN, RED, MAGENTA, BROWN, LIGHTGRAY, DARKGRAY,
LIGHTBLUE, LIGHTGREEN, LIGHTCYAN, LIGHTRED, LIGHTMAGENTA, YELLOW, WHITE };
// The standard line styles
enum line_styles { SOLID_LINE, DOTTED_LINE, CENTER_LINE, DASHED_LINE, USERBIT_LINE };
// The standard fill styles
enum fill_styles { EMPTY_FILL, SOLID_FILL, LINE_FILL, LTSLASH_FILL, SLASH_FILL,
BKSLASH_FILL, LTBKSLASH_FILL, HATCH_FILL, XHATCH_FILL, INTERLEAVE_FILL,
WIDE_DOT_FILL, CLOSE_DOT_FILL, USER_FILL };
// The various graphics drivers
enum graphics_drivers { DETECT, CGA, MCGA, EGA, EGA64, EGAMONO, IBM8514, HERCMONO,
ATT400, VGA, PC3270 };
// Various modes for each graphics driver
enum graphics_modes { CGAC0, CGAC1, CGAC2, CGAC3, CGAHI,
MCGAC0 = 0, MCGAC1, MCGAC2, MCGAC3, MCGAMED, MCGAHI,
EGALO = 0, EGAHI,
EGA64LO = 0, EGA64HI,
EGAMONOHI = 3,
HERCMONOHI = 0,
ATT400C0 = 0, ATT400C1, ATT400C2, ATT400C3, ATT400MED, ATT400HI,
VGALO = 0, VGAMED, VGAHI,
PC3270HI = 0,
IBM8514LO = 0, IBM8514HI };
// Borland error messages for the graphics window.
#define NO_CLICK -1 // No mouse event of the current type in getmouseclick
enum graph_errors { grInvalidVersion = -18, grInvalidDeviceNum = -15, grInvalidFontNum,
grInvalidFont, grIOerror, grError, grInvalidMode, grNoFontMem,
grFontNotFound, grNoFloodMem, grNoScanMem, grNoLoadMem,
grInvalidDriver, grFileNotFound, grNotDetected, grNoInitGraph,
grOk };
// Write modes
enum putimage_ops{ COPY_PUT, XOR_PUT, OR_PUT, AND_PUT, NOT_PUT };
// Text Modes
enum horiz { LEFT_TEXT, CENTER_TEXT, RIGHT_TEXT };
enum vertical { BOTTOM_TEXT, VCENTER_TEXT, TOP_TEXT }; // middle not needed other than as seperator
enum font_names { DEFAULT_FONT, TRIPLEX_FONT, SMALL_FONT, SANS_SERIF_FONT,
GOTHIC_FONT, SCRIPT_FONT, SIMPLEX_FONT, TRIPLEX_SCR_FONT,
COMPLEX_FONT, EUROPEAN_FONT, BOLD_FONT };
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// Structures
// ---------------------------------------------------------------------------
// This structure records information about the last call to arc. It is used
// by getarccoords to get the location of the endpoints of the arc.
struct arccoordstype
{
int x, y; // Center point of the arc
int xstart, ystart; // The starting position of the arc
int xend, yend; // The ending position of the arc.
};
// This structure defines the fill style for the current window. Pattern is
// one of the system patterns such as SOLID_FILL. Color is the color to
// fill with
struct fillsettingstype
{
int pattern; // Current fill pattern
int color; // Current fill color
};
// This structure records information about the current line style.
// linestyle is one of the line styles such as SOLID_LINE, upattern is a
// 16-bit pattern for user defined lines, and thickness is the width of the
// line in pixels.
struct linesettingstype
{
int linestyle; // Current line style
unsigned upattern; // 16-bit user line pattern
int thickness; // Width of the line in pixels
};
// This structure records information about the text settings.
struct textsettingstype
{
int font; // The font in use
int direction; // Text direction
int charsize; // Character size
int horiz; // Horizontal text justification
int vert; // Vertical text justification
};
// This structure records information about the viewport
struct viewporttype
{
int left, top, // Viewport bounding box
right, bottom;
int clip; // Whether to clip image to viewport
};
// This structure records information about the palette.
struct palettetype
{
unsigned char size;
signed char colors[MAXCOLORS + 1];
};
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// API Entries
// ---------------------------------------------------------------------------
#ifdef __cplusplus
extern "C" {
#endif
// Drawing Functions
void arc( int x, int y, int stangle, int endangle, int radius );
void bar( int left, int top, int right, int bottom );
void bar3d( int left, int top, int right, int bottom, int depth, int topflag );
void circle( int x, int y, int radius );
void cleardevice( );
void clearviewport( );
void drawpoly(int n_points, int* points);
void ellipse( int x, int y, int stangle, int endangle, int xradius, int yradius );
void fillellipse( int x, int y, int xradius, int yradius );
void fillpoly(int n_points, int* points);
void floodfill( int x, int y, int border );
void line( int x1, int y1, int x2, int y2 );
void linerel( int dx, int dy );
void lineto( int x, int y );
void pieslice( int x, int y, int stangle, int endangle, int radius );
void putpixel( int x, int y, int color );
void rectangle( int left, int top, int right, int bottom );
void sector( int x, int y, int stangle, int endangle, int xradius, int yradius );
// Miscellaneous Functions
int getdisplaycolor( int color );
int converttorgb( int color );
void delay( int msec );
void getarccoords( arccoordstype *arccoords );
int getbkcolor( );
int getcolor( );
void getfillpattern( char *pattern );
void getfillsettings( fillsettingstype *fillinfo );
void getlinesettings( linesettingstype *lineinfo );
int getmaxcolor( );
int getmaxheight( );
int getmaxwidth( );
int getmaxx( );
int getmaxy( );
bool getrefreshingbgi( );
int getwindowheight( );
int getwindowwidth( );
int getpixel( int x, int y );
void getviewsettings( viewporttype *viewport );
int getx( );
int gety( );
void moverel( int dx, int dy );
void moveto( int x, int y );
void refreshbgi(int left, int top, int right, int bottom);
void refreshallbgi( );
void setbkcolor( int color );
void setcolor( int color );
void setfillpattern( char *upattern, int color );
void setfillstyle( int pattern, int color );
void setlinestyle( int linestyle, unsigned upattern, int thickness );
void setrefreshingbgi(bool value);
void setviewport( int left, int top, int right, int bottom, int clip );
void setwritemode( int mode );
// Window Creation / Graphics Manipulation
void closegraph( int wid=ALL_WINDOWS );
void detectgraph( int *graphdriver, int *graphmode );
void getaspectratio( int *xasp, int *yasp );
char *getdrivername( );
int getgraphmode( );
int getmaxmode( );
char *getmodename( int mode_number );
void getmoderange( int graphdriver, int *lomode, int *himode );
void graphdefaults( );
char *grapherrormsg( int errorcode );
int graphresult( );
void initgraph( int *graphdriver, int *graphmode, char *pathtodriver );
int initwindow
( int width, int height, const char* title="Windows BGI", int left=0, int top=0, bool dbflag=false, bool closeflag=true );
int installuserdriver( char *name, int *fp ); // Not available in WinBGI
int installuserfont( char *name ); // Not available in WinBGI
int registerbgidriver( void *driver ); // Not available in WinBGI
int registerbgifont( void *font ); // Not available in WinBGI
void restorecrtmode( );
void setaspectratio( int xasp, int yasp );
unsigned setgraphbufsize( unsigned bufsize ); // Not available in WinBGI
void setgraphmode( int mode );
void showerrorbox( const char *msg = NULL );
// User Interaction
int getch( );
int kbhit( );
// User-Controlled Window Functions (winbgi.cpp)
int getcurrentwindow( );
void setcurrentwindow( int window );
// Double buffering support (winbgi.cpp)
int getactivepage( );
int getvisualpage( );
void setactivepage( int page );
void setvisualpage( int page );
void swapbuffers( );
// Image Functions (drawing.cpp)
unsigned imagesize( int left, int top, int right, int bottom );
void getimage( int left, int top, int right, int bottom, void *bitmap );
void putimage( int left, int top, void *bitmap, int op );
void printimage(
const char* title=NULL,
double width_inches=7, double border_left_inches=0.75, double border_top_inches=0.75,
int left=0, int top=0, int right=INT_MAX, int bottom=INT_MAX,
bool active=true, HWND hwnd=NULL
);
void readimagefile(
const char* filename=NULL,
int left=0, int top=0, int right=INT_MAX, int bottom=INT_MAX
);
void writeimagefile(
const char* filename=NULL,
int left=0, int top=0, int right=INT_MAX, int bottom=INT_MAX,
bool active=true, HWND hwnd=NULL
);
// Text Functions (text.cpp)
void gettextsettings(struct textsettingstype *texttypeinfo);
void outtext(char *textstring);
void outtextxy(int x, int y, char *textstring);
void settextjustify(int horiz, int vert);
void settextstyle(int font, int direction, int charsize);
void setusercharsize(int multx, int divx, int multy, int divy);
int textheight(char *textstring);
int textwidth(char *textstring);
extern std::ostringstream bgiout;
void outstream(std::ostringstream& out=bgiout);
void outstreamxy(int x, int y, std::ostringstream& out=bgiout);
// Mouse Functions (mouse.cpp)
void clearmouseclick( int kind );
void clearresizeevent( );
void getmouseclick( int kind, int& x, int& y );
bool ismouseclick( int kind );
bool isresizeevent( );
int mousex( );
int mousey( );
void registermousehandler( int kind, void h( int, int ) );
void setmousequeuestatus( int kind, bool status=true );
// Palette Functions
palettetype *getdefaultpalette( );
void getpalette( palettetype *palette );
int getpalettesize( );
void setallpalette( palettetype *palette );
void setpalette( int colornum, int color );
void setrgbpalette( int colornum, int red, int green, int blue );
// Color Macros
#define IS_BGI_COLOR(v) ( ((v) >= 0) && ((v) < 16) )
#define IS_RGB_COLOR(v) ( (v) & 0x03000000 )
#define RED_VALUE(v) int(GetRValue( converttorgb(v) ))
#define GREEN_VALUE(v) int(GetGValue( converttorgb(v) ))
#define BLUE_VALUE(v) int(GetBValue( converttorgb(v) ))
#undef COLOR
int COLOR(int r, int g, int b); // No longer a macro
#ifdef __cplusplus
}
#endif
// ---------------------------------------------------------------------------
#endif // WINBGI_H
+362
View File
@@ -0,0 +1,362 @@
// The winbgim library, Version 6.0, August 9, 2004
// Written by:
// Grant Macklem (Grant.Macklem@colorado.edu)
// Gregory Schmelter (Gregory.Schmelter@colorado.edu)
// Alan Schmidt (Alan.Schmidt@colorado.edu)
// Ivan Stashak (Ivan.Stashak@colorado.edu)
// Michael Main (Michael.Main@colorado.edu)
// CSCI 4830/7818: API Programming
// University of Colorado at Boulder, Spring 2003
// ---------------------------------------------------------------------------
// Notes
// ---------------------------------------------------------------------------
// * This library is still under development.
// * Please see http://www.cs.colorado.edu/~main/bgi for information on
// * using this library with the mingw32 g++ compiler.
// * This library only works with Windows API level 4.0 and higher (Windows 95, NT 4.0 and newer)
// * This library may not be compatible with 64-bit versions of Windows
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// Macro Guard and Include Directives
// ---------------------------------------------------------------------------
#ifndef WINBGI_H
#define WINBGI_H
#include <windows.h> // Provides the mouse message types
#include <limits.h> // Provides INT_MAX
#include <sstream> // Provides std::ostringstream
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// Definitions
// ---------------------------------------------------------------------------
// Definitions for the key pad extended keys are added here. When one
// of these keys are pressed, getch will return a zero followed by one
// of these values. This is the same way that it works in conio for
// dos applications.
#define KEY_HOME 71
#define KEY_UP 72
#define KEY_PGUP 73
#define KEY_LEFT 75
#define KEY_CENTER 76
#define KEY_RIGHT 77
#define KEY_END 79
#define KEY_DOWN 80
#define KEY_PGDN 81
#define KEY_INSERT 82
#define KEY_DELETE 83
#define KEY_F1 59
#define KEY_F2 60
#define KEY_F3 61
#define KEY_F4 62
#define KEY_F5 63
#define KEY_F6 64
#define KEY_F7 65
#define KEY_F8 66
#define KEY_F9 67
// Line thickness settings
#define NORM_WIDTH 1
#define THICK_WIDTH 3
// Character Size and Direction
#define USER_CHAR_SIZE 0
#define HORIZ_DIR 0
#define VERT_DIR 1
// Constants for closegraph
#define CURRENT_WINDOW -1
#define ALL_WINDOWS -2
#define NO_CURRENT_WINDOW -3
// The standard Borland 16 colors
#define MAXCOLORS 15
enum colors { BLACK, BLUE, GREEN, CYAN, RED, MAGENTA, BROWN, LIGHTGRAY, DARKGRAY,
LIGHTBLUE, LIGHTGREEN, LIGHTCYAN, LIGHTRED, LIGHTMAGENTA, YELLOW, WHITE };
// The standard line styles
enum line_styles { SOLID_LINE, DOTTED_LINE, CENTER_LINE, DASHED_LINE, USERBIT_LINE };
// The standard fill styles
enum fill_styles { EMPTY_FILL, SOLID_FILL, LINE_FILL, LTSLASH_FILL, SLASH_FILL,
BKSLASH_FILL, LTBKSLASH_FILL, HATCH_FILL, XHATCH_FILL, INTERLEAVE_FILL,
WIDE_DOT_FILL, CLOSE_DOT_FILL, USER_FILL };
// The various graphics drivers
enum graphics_drivers { DETECT, CGA, MCGA, EGA, EGA64, EGAMONO, IBM8514, HERCMONO,
ATT400, VGA, PC3270 };
// Various modes for each graphics driver
enum graphics_modes { CGAC0, CGAC1, CGAC2, CGAC3, CGAHI,
MCGAC0 = 0, MCGAC1, MCGAC2, MCGAC3, MCGAMED, MCGAHI,
EGALO = 0, EGAHI,
EGA64LO = 0, EGA64HI,
EGAMONOHI = 3,
HERCMONOHI = 0,
ATT400C0 = 0, ATT400C1, ATT400C2, ATT400C3, ATT400MED, ATT400HI,
VGALO = 0, VGAMED, VGAHI,
PC3270HI = 0,
IBM8514LO = 0, IBM8514HI };
// Borland error messages for the graphics window.
#define NO_CLICK -1 // No mouse event of the current type in getmouseclick
enum graph_errors { grInvalidVersion = -18, grInvalidDeviceNum = -15, grInvalidFontNum,
grInvalidFont, grIOerror, grError, grInvalidMode, grNoFontMem,
grFontNotFound, grNoFloodMem, grNoScanMem, grNoLoadMem,
grInvalidDriver, grFileNotFound, grNotDetected, grNoInitGraph,
grOk };
// Write modes
enum putimage_ops{ COPY_PUT, XOR_PUT, OR_PUT, AND_PUT, NOT_PUT };
// Text Modes
enum horiz { LEFT_TEXT, CENTER_TEXT, RIGHT_TEXT };
enum vertical { BOTTOM_TEXT, VCENTER_TEXT, TOP_TEXT }; // middle not needed other than as seperator
enum font_names { DEFAULT_FONT, TRIPLEX_FONT, SMALL_FONT, SANS_SERIF_FONT,
GOTHIC_FONT, SCRIPT_FONT, SIMPLEX_FONT, TRIPLEX_SCR_FONT,
COMPLEX_FONT, EUROPEAN_FONT, BOLD_FONT };
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// Structures
// ---------------------------------------------------------------------------
// This structure records information about the last call to arc. It is used
// by getarccoords to get the location of the endpoints of the arc.
struct arccoordstype
{
int x, y; // Center point of the arc
int xstart, ystart; // The starting position of the arc
int xend, yend; // The ending position of the arc.
};
// This structure defines the fill style for the current window. Pattern is
// one of the system patterns such as SOLID_FILL. Color is the color to
// fill with
struct fillsettingstype
{
int pattern; // Current fill pattern
int color; // Current fill color
};
// This structure records information about the current line style.
// linestyle is one of the line styles such as SOLID_LINE, upattern is a
// 16-bit pattern for user defined lines, and thickness is the width of the
// line in pixels.
struct linesettingstype
{
int linestyle; // Current line style
unsigned upattern; // 16-bit user line pattern
int thickness; // Width of the line in pixels
};
// This structure records information about the text settings.
struct textsettingstype
{
int font; // The font in use
int direction; // Text direction
int charsize; // Character size
int horiz; // Horizontal text justification
int vert; // Vertical text justification
};
// This structure records information about the viewport
struct viewporttype
{
int left, top, // Viewport bounding box
right, bottom;
int clip; // Whether to clip image to viewport
};
// This structure records information about the palette.
struct palettetype
{
unsigned char size;
signed char colors[MAXCOLORS + 1];
};
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// API Entries
// ---------------------------------------------------------------------------
#ifdef __cplusplus
extern "C" {
#endif
// Drawing Functions
void arc( int x, int y, int stangle, int endangle, int radius );
void bar( int left, int top, int right, int bottom );
void bar3d( int left, int top, int right, int bottom, int depth, int topflag );
void circle( int x, int y, int radius );
void cleardevice( );
void clearviewport( );
void drawpoly(int n_points, int* points);
void ellipse( int x, int y, int stangle, int endangle, int xradius, int yradius );
void fillellipse( int x, int y, int xradius, int yradius );
void fillpoly(int n_points, int* points);
void floodfill( int x, int y, int border );
void line( int x1, int y1, int x2, int y2 );
void linerel( int dx, int dy );
void lineto( int x, int y );
void pieslice( int x, int y, int stangle, int endangle, int radius );
void putpixel( int x, int y, int color );
void rectangle( int left, int top, int right, int bottom );
void sector( int x, int y, int stangle, int endangle, int xradius, int yradius );
// Miscellaneous Functions
int getdisplaycolor( int color );
int converttorgb( int color );
void delay( int msec );
void getarccoords( arccoordstype *arccoords );
int getbkcolor( );
int getcolor( );
void getfillpattern( char *pattern );
void getfillsettings( fillsettingstype *fillinfo );
void getlinesettings( linesettingstype *lineinfo );
int getmaxcolor( );
int getmaxheight( );
int getmaxwidth( );
int getmaxx( );
int getmaxy( );
bool getrefreshingbgi( );
int getwindowheight( );
int getwindowwidth( );
int getpixel( int x, int y );
void getviewsettings( viewporttype *viewport );
int getx( );
int gety( );
void moverel( int dx, int dy );
void moveto( int x, int y );
void refreshbgi(int left, int top, int right, int bottom);
void refreshallbgi( );
void setbkcolor( int color );
void setcolor( int color );
void setfillpattern( char *upattern, int color );
void setfillstyle( int pattern, int color );
void setlinestyle( int linestyle, unsigned upattern, int thickness );
void setrefreshingbgi(bool value);
void setviewport( int left, int top, int right, int bottom, int clip );
void setwritemode( int mode );
// Window Creation / Graphics Manipulation
void closegraph( int wid=ALL_WINDOWS );
void detectgraph( int *graphdriver, int *graphmode );
void getaspectratio( int *xasp, int *yasp );
char *getdrivername( );
int getgraphmode( );
int getmaxmode( );
char *getmodename( int mode_number );
void getmoderange( int graphdriver, int *lomode, int *himode );
void graphdefaults( );
char *grapherrormsg( int errorcode );
int graphresult( );
void initgraph( int *graphdriver, int *graphmode, char *pathtodriver );
int initwindow
( int width, int height, const char* title="Windows BGI", int left=0, int top=0, bool dbflag=false, bool closeflag=true );
int installuserdriver( char *name, int *fp ); // Not available in WinBGI
int installuserfont( char *name ); // Not available in WinBGI
int registerbgidriver( void *driver ); // Not available in WinBGI
int registerbgifont( void *font ); // Not available in WinBGI
void restorecrtmode( );
void setaspectratio( int xasp, int yasp );
unsigned setgraphbufsize( unsigned bufsize ); // Not available in WinBGI
void setgraphmode( int mode );
void showerrorbox( const char *msg = NULL );
// User Interaction
int getch( );
int kbhit( );
// User-Controlled Window Functions (winbgi.cpp)
int getcurrentwindow( );
void setcurrentwindow( int window );
// Double buffering support (winbgi.cpp)
int getactivepage( );
int getvisualpage( );
void setactivepage( int page );
void setvisualpage( int page );
void swapbuffers( );
// Image Functions (drawing.cpp)
unsigned imagesize( int left, int top, int right, int bottom );
void getimage( int left, int top, int right, int bottom, void *bitmap );
void putimage( int left, int top, void *bitmap, int op );
void printimage(
const char* title=NULL,
double width_inches=7, double border_left_inches=0.75, double border_top_inches=0.75,
int left=0, int top=0, int right=INT_MAX, int bottom=INT_MAX,
bool active=true, HWND hwnd=NULL
);
void readimagefile(
const char* filename=NULL,
int left=0, int top=0, int right=INT_MAX, int bottom=INT_MAX
);
void writeimagefile(
const char* filename=NULL,
int left=0, int top=0, int right=INT_MAX, int bottom=INT_MAX,
bool active=true, HWND hwnd=NULL
);
// Text Functions (text.cpp)
void gettextsettings(struct textsettingstype *texttypeinfo);
void outtext(char *textstring);
void outtextxy(int x, int y, char *textstring);
void settextjustify(int horiz, int vert);
void settextstyle(int font, int direction, int charsize);
void setusercharsize(int multx, int divx, int multy, int divy);
int textheight(char *textstring);
int textwidth(char *textstring);
extern std::ostringstream bgiout;
void outstream(std::ostringstream& out=bgiout);
void outstreamxy(int x, int y, std::ostringstream& out=bgiout);
// Mouse Functions (mouse.cpp)
void clearmouseclick( int kind );
void clearresizeevent( );
void getmouseclick( int kind, int& x, int& y );
bool ismouseclick( int kind );
bool isresizeevent( );
int mousex( );
int mousey( );
void registermousehandler( int kind, void h( int, int ) );
void setmousequeuestatus( int kind, bool status=true );
// Palette Functions
palettetype *getdefaultpalette( );
void getpalette( palettetype *palette );
int getpalettesize( );
void setallpalette( palettetype *palette );
void setpalette( int colornum, int color );
void setrgbpalette( int colornum, int red, int green, int blue );
// Color Macros
#define IS_BGI_COLOR(v) ( ((v) >= 0) && ((v) < 16) )
#define IS_RGB_COLOR(v) ( (v) & 0x03000000 )
#define RED_VALUE(v) int(GetRValue( converttorgb(v) ))
#define GREEN_VALUE(v) int(GetGValue( converttorgb(v) ))
#define BLUE_VALUE(v) int(GetBValue( converttorgb(v) ))
#undef COLOR
int COLOR(int r, int g, int b); // No longer a macro
#ifdef __cplusplus
}
#endif
// ---------------------------------------------------------------------------
#endif // WINBGI_H
+126
View File
@@ -0,0 +1,126 @@
0.000000 0.000000
320.000000 240.000000
0.100000 0.099833
325.000000 236.006663
0.200000 0.198669
330.000000 232.053227
0.300000 0.295520
335.000000 228.179192
0.400000 0.389418
340.000000 224.423266
0.500000 0.479426
345.000000 220.822978
0.600000 0.564642
350.000000 217.414301
0.700000 0.644218
355.000000 214.231293
0.800000 0.717356
360.000000 211.305756
0.900000 0.783327
365.000000 208.666924
1.000000 0.841471
370.000000 206.341161
1.100000 0.891207
375.000000 204.351706
1.200000 0.932039
380.000000 202.718437
1.300000 0.963558
385.000000 201.457673
1.400000 0.985450
390.000000 200.582011
1.500000 0.997495
395.000000 200.100201
1.600000 0.999574
400.000000 200.017056
1.700000 0.991665
405.000000 200.333408
1.800000 0.973848
410.000000 201.046095
1.900000 0.946300
415.000000 202.147996
2.000000 0.909297
420.000000 203.628103
2.100000 0.863209
425.000000 205.471625
2.200000 0.808496
430.000000 207.660144
2.300000 0.745705
435.000000 210.171792
2.400000 0.675463
440.000000 212.981473
2.500000 0.598472
445.000000 216.061114
2.600000 0.515501
450.000000 219.379945
2.700000 0.427380
455.000000 222.904805
2.800000 0.334988
460.000000 226.600474
2.900000 0.239249
465.000000 230.430027
3.000000 0.141120
470.000000 234.355200
3.100000 0.041581
475.000000 238.336774
3.200000 -0.058374
480.000000 242.334966
3.300000 -0.157746
485.000000 246.309828
3.400000 -0.255541
490.000000 250.221644
3.500000 -0.350783
495.000000 254.031329
3.600000 -0.442520
500.000000 257.700818
3.700000 -0.529836
505.000000 261.193446
3.800000 -0.611858
510.000000 264.474316
3.900000 -0.687766
515.000000 267.510646
4.000000 -0.756802
520.000000 270.272100
4.100000 -0.818277
525.000000 272.731084
4.200000 -0.871576
530.000000 274.863031
4.300000 -0.916166
535.000000 276.646637
4.400000 -0.951602
540.000000 278.064083
4.500000 -0.977530
545.000000 279.101205
4.600000 -0.993691
550.000000 279.747640
4.700000 -0.999923
555.000000 279.996930
4.800000 -0.996165
560.000000 279.846584
4.900000 -0.982453
565.000000 279.298105
5.000000 -0.958924
570.000000 278.356971
5.100000 -0.925815
575.000000 277.032587
5.200000 -0.883455
580.000000 275.338186
5.300000 -0.832267
585.000000 273.290698
5.400000 -0.772764
590.000000 270.910580
5.500000 -0.705540
595.000000 268.221613
5.600000 -0.631267
600.000000 265.250666
5.700000 -0.550686
605.000000 262.027422
5.800000 -0.464602
610.000000 258.584087
5.900000 -0.373877
615.000000 254.955067
6.000000 -0.279415
620.000000 251.176620
6.100000 -0.182163
625.000000 247.286500
6.200000 -0.083089
630.000000 243.323576
+63
View File
@@ -0,0 +1,63 @@
0.000000 0.000000
0.100000 0.099833
0.200000 0.198669
0.300000 0.295520
0.400000 0.389418
0.500000 0.479426
0.600000 0.564642
0.700000 0.644218
0.800000 0.717356
0.900000 0.783327
1.000000 0.841471
1.100000 0.891207
1.200000 0.932039
1.300000 0.963558
1.400000 0.985450
1.500000 0.997495
1.600000 0.999574
1.700000 0.991665
1.800000 0.973848
1.900000 0.946300
2.000000 0.909297
2.100000 0.863209
2.200000 0.808496
2.300000 0.745705
2.400000 0.675463
2.500000 0.598472
2.600000 0.515501
2.700000 0.427380
2.800000 0.334988
2.900000 0.239249
3.000000 0.141120
3.100000 0.041581
3.200000 -0.058374
3.300000 -0.157746
3.400000 -0.255541
3.500000 -0.350783
3.600000 -0.442520
3.700000 -0.529836
3.800000 -0.611858
3.900000 -0.687766
4.000000 -0.756802
4.100000 -0.818277
4.200000 -0.871576
4.300000 -0.916166
4.400000 -0.951602
4.500000 -0.977530
4.600000 -0.993691
4.700000 -0.999923
4.800000 -0.996165
4.900000 -0.982453
5.000000 -0.958924
5.100000 -0.925815
5.200000 -0.883455
5.300000 -0.832267
5.400000 -0.772764
5.500000 -0.705540
5.600000 -0.631267
5.700000 -0.550686
5.800000 -0.464602
5.900000 -0.373877
6.000000 -0.279415
6.100000 -0.182163
6.200000 -0.083089
+21
View File
@@ -0,0 +1,21 @@
{
"configurations": [
{
"name": "Win32",
"includePath": [
"${workspaceFolder}/**"
],
"defines": [
"_DEBUG",
"UNICODE",
"_UNICODE"
],
"windowsSdkVersion": "10.0.18362.0",
"compilerPath": "cl.exe",
"cStandard": "c17",
"cppStandard": "c++17",
"intelliSenseMode": "windows-msvc-x64"
}
],
"version": 4
}
+58
View File
@@ -0,0 +1,58 @@
{
"files.associations": {
"iosfwd": "cpp",
"iostream": "cpp",
"atomic": "cpp",
"bit": "cpp",
"cctype": "cpp",
"charconv": "cpp",
"clocale": "cpp",
"cmath": "cpp",
"compare": "cpp",
"concepts": "cpp",
"cstddef": "cpp",
"cstdint": "cpp",
"cstdio": "cpp",
"cstdlib": "cpp",
"cstring": "cpp",
"ctime": "cpp",
"cwchar": "cpp",
"exception": "cpp",
"format": "cpp",
"fstream": "cpp",
"initializer_list": "cpp",
"ios": "cpp",
"istream": "cpp",
"iterator": "cpp",
"limits": "cpp",
"locale": "cpp",
"memory": "cpp",
"mutex": "cpp",
"new": "cpp",
"ostream": "cpp",
"ratio": "cpp",
"stdexcept": "cpp",
"stop_token": "cpp",
"streambuf": "cpp",
"system_error": "cpp",
"thread": "cpp",
"tuple": "cpp",
"type_traits": "cpp",
"typeinfo": "cpp",
"utility": "cpp",
"xfacet": "cpp",
"xiosbase": "cpp",
"xlocale": "cpp",
"xlocbuf": "cpp",
"xlocinfo": "cpp",
"xlocmes": "cpp",
"xlocmon": "cpp",
"xlocnum": "cpp",
"xloctime": "cpp",
"xmemory": "cpp",
"xstring": "cpp",
"xtr1common": "cpp",
"xutility": "cpp",
"vector": "cpp"
}
}
+28
View File
@@ -0,0 +1,28 @@
{
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: g++.exe build active file",
"command": "D:\\mingw\\MinGW\\bin\\g++.exe",
"args": [
"-fdiagnostics-color=always",
"-g",
"${file}",
"-o",
"${fileDirname}\\${fileBasenameNoExtension}.exe"
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "Task generated by Debugger."
}
],
"version": "2.0.0"
}
+81
View File
@@ -0,0 +1,81 @@
/*
1.Постоянный ввод целых чисел. «0» – конец ввода, или пока не закончится файл. Найти:
- количество чисел;
- минимальное, максимальное и среднее значения;
- количество положительных и отрицательных чисел.
результат вывести на экран/в файл
*/
#include <iostream>
#include <fstream>
class Task {
private:
struct Statistic {
int count = 0;
int minimum = INT_MAX;
int maximum = INT_MIN;
int summary = 0;
int positive = 0;
int negative = 0;
double average = 0;
} _statistic;
int _number;
std::ifstream _file_in;
std::ofstream _file_out;
void _setStatistic() {
while (_file_in >> _number) {
if (_number == 0)
break;
_statistic.count++;
_statistic.summary += _number;
if (_number < _statistic.minimum)
_statistic.minimum = _number;
if (_number > _statistic.maximum)
_statistic.maximum = _number;
if (_number > 0)
_statistic.positive++;
if (_number < 0)
_statistic.negative++;
}
_statistic.average = static_cast<double>(_statistic.summary) / _statistic.count;
}
public:
Task(const std::string filename_input = "input.txt", const std::string filename_output = "output.txt") {
_file_in.open(filename_input);
_file_out.open(filename_output);
if (!_file_in.is_open() || !_file_out.is_open()) {
std::cerr << "Ошибка открытия файла" << std::endl;
exit(1);
}
_setStatistic();
}
~Task() {
_file_in.close();
_file_out.close();
}
void writeData() {
_file_out << "Количество чисел: " << _statistic.count << std::endl;
_file_out << "Минимальное значение: " << _statistic.minimum << std::endl;
_file_out << "Максимальное значение: " << _statistic.maximum << std::endl;
_file_out << "Среднее значение: " << _statistic.average << std::endl;
_file_out << "Количество положительных чисел: " << _statistic.positive << std::endl;
_file_out << "Количество отрицательных чисел: " << _statistic.negative << std::endl;
}
};
int main() {
Task task;
task.writeData();
return 0;
}
+108
View File
@@ -0,0 +1,108 @@
/*
2.Разработать класс Rectangle, обладающий следующим функционалом:
- задание сторон вручную/ из файла
- задание сторон координатами вручную/ из файла
- вычисление площади – вывод на экран / в файл
- вычисление периметра – вывод на экран / в файл
- вывод на экран / в файл:
a = …, b = …., P =…, S = …
или
(x1, y1) = …, (x2, y2) = …, P = …, S = …
*/
#include <cmath>
#include <fstream>
#include <iostream>
#include <vector>
class Rectangle {
private:
std::ifstream _file_in;
std::ofstream _file_out;
struct RectangleData {
int width, height;
int perimetr, area;
int x1, y1;
int x2, y2;
} _rectangleData;
bool _isCoordinate;
void _init(const std::string filename_input,
const std::string filename_output) {
_file_in.open(filename_input);
_file_out.open(filename_output);
if (!_file_in.is_open() || !_file_out.is_open()) {
std::cerr << "Ошибка открытия файла" << std::endl;
exit(1);
}
}
void _setWidthHeightfromXY() {
_rectangleData.width = abs(_rectangleData.y2 - _rectangleData.y1);
_rectangleData.height = abs(_rectangleData.x2 - _rectangleData.x1);
}
void _setPerimetr() {
_rectangleData.perimetr =
(_rectangleData.width + _rectangleData.height) * 2;
}
void _setArea() {
_rectangleData.area = _rectangleData.width * _rectangleData.height;
}
public:
Rectangle(const std::string filename_input = "input.txt",
const std::string filename_output = "output.txt") {
_init(filename_input, filename_output);
std::vector<int> buffer;
int number;
while (_file_in >> number) {
buffer.push_back(number);
}
const int length = buffer.size();
_isCoordinate = (length == 4) ? true : false;
if (_isCoordinate) {
_rectangleData.x1 = buffer[0];
_rectangleData.y1 = buffer[1];
_rectangleData.x2 = buffer[2];
_rectangleData.y2 = buffer[3];
_setWidthHeightfromXY();
} else {
_rectangleData.width = buffer[0];
_rectangleData.height = buffer[1];
}
_setPerimetr();
_setArea();
}
void writeData() {
if (_isCoordinate) {
_file_out << "(x1, y1) = (" << _rectangleData.x1 << ", "
<< _rectangleData.y1 << "), (x2, y2) = ("
<< _rectangleData.x2 << ", " << _rectangleData.y2 << ")";
} else {
_file_out << "a = " << _rectangleData.width
<< ", b = " << _rectangleData.height;
}
_file_out << ", "
<< "P = " << _rectangleData.perimetr << ", "
<< "S = " << _rectangleData.area;
}
};
int main() {
Rectangle rect;
rect.writeData();
return 0;
}
Binary file not shown.
+2
View File
@@ -0,0 +1,2 @@
0 0
5 2
+1
View File
@@ -0,0 +1 @@
(x1, y1) = (0, 0), (x2, y2) = (5, 2), P = 14, S = 10
@@ -0,0 +1,108 @@
#include <stdio.h>
#include <graphics.h>
#include <math.h>
#include <winbgim.h>
int main() {
// Êîîðäèíàòû òî÷åê A(-6, 4), B(-2, -2), C(-1, -4), D(2, 3)
int ax = -6, ay = 4, bx = -2, by = -2;
int cx = -1, cy = -4, dx = 2, dy = 3;
// Âåêòîð a ñ êîîðäèíàòàìè (B-A) è âåêòîð b ñ êîîðäèíàòàìè (D-C)
int vecA_x = bx - ax;
int vecA_y = by - ay;
int vecB_x = dx - cx;
int vecB_y = dy - cy;
// Óìíîæàåì âåêòîð a íà 2
int vec2A_x = 2 * vecA_x;
int vec2A_y = 2 * vecA_y;
// Ñêàëÿðíîå ïðîèçâåäåíèå
int scalarProduct = vec2A_x * vecB_x + vec2A_y * vecB_y;
// Îòêðûâàåì ôàéë äëÿ çàïèñè
FILE *file = fopen("Îòâåò.txt", "w");
if (file != NULL) {
fprintf(file, "Solution to the scalar product task:\n");
fprintf(file, "Vector A: (%d, %d)\n", ax, ay);
fprintf(file, "Vector B: (%d, %d)\n", bx, by);
fprintf(file, "Vector C: (%d, %d)\n", cx, cy);
fprintf(file, "Vector D: (%d, %d)\n", dx, dy);
fprintf(file, "Scalar product of 2a and b: %d\n", scalarProduct);
fclose(file); // Çàêðûâàåì ôàéë
} else {
printf("Error opening file!\n");
}
// Èíèöèàëèçàöèÿ ãðàôèêè
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
// Ìàñøòàáèðîâàíèå
int scale = 30; // Øàã ñåòêè
// Ñìåùàåì íà÷àëî êîîðäèíàò â áëèæàéøóþ êëåòî÷êó
int origin_x = (getmaxx() / 2) / scale * scale; // Áëèæàéøàÿ êëåòêà ïî x
int origin_y = (getmaxy() / 2) / scale * scale; // Áëèæàéøàÿ êëåòêà ïî y
// Ðèñóåì êëåòî÷íóþ ñåòêó
setcolor(12); // Öâåò äëÿ ñåòêè
for (int i = 0; i < getmaxx(); i += scale) {
line(i, 0, i, getmaxy()); // Âåðòèêàëüíûå ëèíèè
}
for (int i = 0; i < getmaxy(); i += scale) {
line(0, i, getmaxx(), i); // Ãîðèçîíòàëüíûå ëèíèè
}
// Ðèñóåì îñè êîîðäèíàò, ñìåùåííûå ê áëèæàéøåé êëåòêå
setcolor(5);
line(0, origin_y, getmaxx(), origin_y); // Îñü X
line(origin_x, 0, origin_x, getmaxy()); // Îñü Y
// Ðèñóåì âåêòîð AB èç òî÷êè A
setcolor(RED); // Öâåò äëÿ âåêòîðà AB
line(origin_x + ax * scale, origin_y - ay * scale,
origin_x + bx * scale, origin_y - by * scale);
// Ðèñóåì âåêòîð CD èç òî÷êè C
setcolor(BLUE); // Öâåò äëÿ âåêòîðà CD
line(origin_x + cx * scale, origin_y - cy * scale,
origin_x + dx * scale, origin_y - dy * scale);
// Ïîäïèñè òî÷åê A, B, C, D (êàê íà ïðèìåðå)
setcolor(WHITE); // Âåðíóòü áåëûé öâåò äëÿ ïîäïèñåé
outtextxy(origin_x + ax * scale - 20, origin_y - ay * scale, "A");
outtextxy(origin_x + bx * scale + 10, origin_y - by * scale + 5, "B");
outtextxy(origin_x + cx * scale - 20, origin_y - cy * scale, "C");
outtextxy(origin_x + dx * scale + 10, origin_y - dy * scale + 5, "D");
// Ôîðìèðóåì ïîëíîå ðåøåíèå â âèäå òåêñòà
char solutionText[500];
sprintf(solutionText, "Ðåøåíèå:\n"
"A(%d, %d), B(%d, %d)\n"
"C(%d, %d), D(%d, %d)\n"
"2a = (2*(%d, %d))\n"
"b = (%d, %d)\n"
"Îòâåò = %d",
ax, ay, bx, by, cx, cy, dx, dy,
vecA_x, vecA_y, vecB_x, vecB_y, scalarProduct);
// Âûâîä ðåøåíèÿ â ïðàâîì âåðõíåì óãëó
int screen_width = getmaxx(); // Ïîëó÷àåì øèðèíó ýêðàíà
int line_height = 15; // Âûñîòà ñòðîêè
int y_offset = 10; // Íà÷àëüíàÿ ïîçèöèÿ ïî Y
char *line = strtok(solutionText, "\n");
while (line != NULL) {
outtextxy(screen_width - 300, y_offset, line); // Âûâîäèì ñòðîêó
y_offset += line_height; // Ñìåùàåìñÿ ïî Y
line = strtok(NULL, "\n");
}
// Îæèäàíèå íàæàòèÿ êëàâèøè
getch();
closegraph();
return 0;
}
@@ -0,0 +1,85 @@
#include <graphics.h>
#include <conio.h>
#include <stdio.h>
#include <math.h>
#include <winbgim.h> // Äëÿ ðàáîòû ñ ãðàôèêîé
int main() {
// Èíèöèàëèçàöèÿ ãðàôè÷åñêîãî ðåæèìà
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
// Äàííûå çàäà÷è
float initial_volume = 6.0; // Íà÷àëüíûé îáúåì
float factor = 1.6; // Êîýôôèöèåíò óâåëè÷åíèÿ îáúåìà
// Íîâûé îáúåì è îáúåì äåòàëè
float new_volume = initial_volume * factor;
float detail_volume = new_volume - initial_volume;
// Ïàðàìåòðû äëÿ îòðèñîâêè ñîñóäà
int x_center = getmaxx() / 2;
int y_bottom = getmaxy() / 2 + 100;
// Îòðèñîâêà ñîñóäà
rectangle(x_center - 50, y_bottom - 200, x_center + 50, y_bottom);
setfillstyle(SOLID_FILL, LIGHTBLUE);
// Ðàñ÷åò âûñîòû íà÷àëüíîãî óðîâíÿ âîäû
int initial_water_height = 200 * (initial_volume / new_volume);
bar(x_center - 50, y_bottom - initial_water_height, x_center + 50, y_bottom);
// Çàïîëíåíèå âîäîé
setfillstyle(SOLID_FILL, BLUE);
bar(x_center - 50, y_bottom - 200, x_center + 50, y_bottom);
// Ïîäïèñè ê óðîâíÿì âîäû
outtextxy(x_center - 30, y_bottom + 10, "Ñîñóä");
outtextxy(x_center - 30, y_bottom - initial_water_height - 20, "Óðîâåíü 6 êóá. ñì");
outtextxy(x_center - 30, y_bottom - 220, "Óðîâåíü 9.6 êóá. ñì");
// Âûâîä òåêñòà íà ýêðàí (îáúåì äåòàëè) â ëåâîì âåðõíåì óãëó
setcolor(WHITE);
outtextxy(10, 10, "Îáúåì äåòàëè = 3.6 êóá. ñì");
// Ôîðìèðîâàíèå ïîëíîãî òåêñòà ðåøåíèÿ è îòâåòà
char solutionText[500];
sprintf(solutionText, "Ðåøåíèå çàäà÷è:\n"
"Íà÷àëüíûé îáúåì âîäû: %.2f êóá. ñì\n"
"Íîâûé îáúåì âîäû: %.2f êóá. ñì\n"
"Îáúåì äåòàëè: %.2f êóá. ñì",
initial_volume, new_volume, detail_volume);
// Âûâîä ðåøåíèÿ â ïðàâîì âåðõíåì óãëó
int screen_width = getmaxx();
int line_height = 15;
int y_offset = 10;
char *line = strtok(solutionText, "\n");
while (line != NULL) {
outtextxy(screen_width - 300, y_offset, line);
y_offset += line_height;
line = strtok(NULL, "\n");
}
// Çàïèñü ðåøåíèÿ â ôàéë "Îòâåò.txt"
FILE *file = fopen("Îòâåò.txt", "w");
if (file == NULL) {
printf("Îøèáêà ïðè îòêðûòèè ôàéëà!\n");
return 1;
}
fprintf(file, "Ðåøåíèå çàäà÷è:\n");
fprintf(file, "Íà÷àëüíûé îáúåì âîäû = %.2f êóá. ñì\n", initial_volume);
fprintf(file, "Íîâûé îáúåì âîäû ïîñëå ïîãðóæåíèÿ äåòàëè = %.2f êóá. ñì\n", new_volume);
fprintf(file, "Îáúåì äåòàëè = %.2f êóá. ñì\n", detail_volume);
fclose(file);
printf("Îòâåò çàïèñàí â ôàéë 'Îòâåò.txt'.\n");
// Îæèäàíèå ââîäà äëÿ çàêðûòèÿ ãðàôè÷åñêîãî îêíà
getch();
closegraph();
return 0;
}
Binary file not shown.
@@ -0,0 +1,113 @@
#include <graphics.h>
#include <conio.h>
#include <stdio.h>
#include <math.h>
#include <winbgim.h> // Äëÿ ðàáîòû ñ ãðàôèêîé íà Windows
int main() {
// Èíèöèàëèçàöèÿ ãðàôè÷åñêîãî ðåæèìà
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
// Äàííûå çàäà÷è
int angle_ACB = 33; // Óãîë ACB
int arc_AB = 102; // Ãðàäóñíàÿ ìåðà äóãè AB
int angle_DAE = arc_AB / 2; // Óãîë DAE = ïîëîâèíà äóãè AB
// Öåíòð îêðóæíîñòè è ðàäèóñ
int x_center = getmaxx() / 2;
int y_center = getmaxy() / 2;
int radius = 150;
// Îòðèñîâêà îêðóæíîñòè
circle(x_center, y_center, radius);
// Êîîðäèíàòû òî÷åê A, B, C, D
int x_A = x_center;
int y_A = y_center + radius;
int x_B = x_center - radius * cos(M_PI / 10);
int y_B = y_center - radius * sin(M_PI / -1);
int x_C = x_center + radius * 1.5;
int y_C = y_center - radius * 1.5;
int x_D = x_center + radius * cos(M_PI / 3);
int y_D = y_center - radius * sin(M_PI / 3);
// Òåïåðü ðàññ÷èòûâàåì êîîðäèíàòû E, êîòîðàÿ äîëæíà ëåæàòü íà ëèíèè AC
// Èñïîëüçóåì ëèíåéíóþ èíòåðïîëÿöèþ äëÿ íàõîæäåíèÿ êîîðäèíàò E
float ratio = 0.6; // Ïóñòü E áóäåò íà ñåðåäèíå îòðåçêà AC
int x_E = x_A + ratio * (x_C - x_A); // Êîîðäèíàòà X
int y_E = y_A + ratio * (y_C - y_A); // Êîîðäèíàòà Y
// Îòðèñîâêà òî÷åê A, B, C, D, E
setcolor(WHITE);
circle(x_A, y_A, 5);
outtextxy(x_A - 20, y_A + 10, "A");
circle(x_B, y_B, 5);
outtextxy(x_B - 20, y_B - 20, "B");
circle(x_C, y_C, 5);
outtextxy(x_C + 10, y_C - 20, "C");
circle(x_D, y_D, 5);
outtextxy(x_D + 10, y_D - 20, "D");
circle(x_E, y_E, 5);
outtextxy(x_E - 20, y_E + -5, "E");
// Îòðèñîâêà ëèíèé ìåæäó òî÷êàìè
line(x_B, y_B, x_C, y_C); // Ëèíèÿ BC
line(x_D, y_D, x_C, y_C); // Ëèíèÿ DC
line(x_A, y_A, x_D, y_D); // Ëèíèÿ AD
line(x_A, y_A, x_E, y_E); // Ëèíèÿ AE
line(x_D, y_D, x_B, y_B); // Ëèíèÿ DB
// Íîâàÿ ëèíèÿ: ñîåäèíåíèå E, A è C
line(x_E, y_E, x_A, y_A); // Ëèíèÿ îò E ê A
line(x_A, y_A, x_C, y_C); // Ëèíèÿ îò A ê C
// Ïåðåíîñ òåêñòà ðåøåíèÿ â ëåâûé âåðõíèé óãîë
char solutionText[500];
sprintf(solutionText, "Ðåøåíèå çàäà÷è:\n"
"Óãîë ACB = %d ãðàäóñîâ\n"
"Ãðàäóñíàÿ ìåðà äóãè AB = %d ãðàäóñîâ\n"
"Óãîë DAE = %d ãðàäóñîâ",
angle_ACB, arc_AB, angle_DAE);
// Âûâîä ðåøåíèÿ â ëåâîì âåðõíåì óãëó
int screen_width = getmaxx();
int line_height = 15;
int y_offset = 10;
char *line = strtok(solutionText, "\n");
while (line != NULL) {
outtextxy(10, y_offset, line); // Ëåâûé âåðõíèé óãîë
y_offset += line_height;
line = strtok(NULL, "\n");
}
// Çàïèñü ðåøåíèÿ â ôàéë "Îòâåò.txt"
FILE *file = fopen("Îòâåò.txt", "w");
if (file == NULL) {
printf("Îøèáêà ïðè îòêðûòèè ôàéëà!\n");
return 1;
}
fprintf(file, "Ðåøåíèå çàäà÷è:\n");
fprintf(file, "Óãîë ACB = %d ãðàäóñîâ\n", angle_ACB);
fprintf(file, "Ãðàäóñíàÿ ìåðà äóãè AB = %d ãðàäóñîâ\n", arc_AB);
fprintf(file, "Óãîë DAE = %d ãðàäóñîâ\n", angle_DAE);
fclose(file);
printf("Îòâåò çàïèñàí â ôàéë 'Îòâåò.txt'.\n");
// Îæèäàíèå ââîäà äëÿ çàêðûòèÿ ãðàôè÷åñêîãî îêíà
getch();
closegraph();
return 0;
}
Binary file not shown.
@@ -0,0 +1,125 @@
#include <graphics.h>
#include <conio.h>
#include <stdio.h>
#include <math.h>
#include <winbgim.h> // Äëÿ ðàáîòû ñ ãðàôèêîé íà Windows
// Ôóíêöèÿ äëÿ ðàñ÷åòà çíà÷åíèÿ y = (x + 4)^2(x + 3) - 6
double func(double x) {
return pow((x + 4), 2) * (x + 3) - 6;
}
int main() {
// Èíèöèàëèçàöèÿ ãðàôè÷åñêîãî ðåæèìà
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
// Óñëîâèå çàäà÷è
setcolor(WHITE);
outtextxy(10, 10, "Íàéäèòå íàèáîëüøåå çíà÷åíèå ôóíêöèè y = (x+4)^2(x+3) - 6");
outtextxy(10, 30, "íà îòðåçêå [-5, -3.5].");
// Íàéäåì çíà÷åíèÿ ôóíêöèè â ãðàíè÷íûõ òî÷êàõ è êðèòè÷åñêèõ òî÷êàõ
double x1 = -5, x2 = -3.5;
double x_critical1 = -4, x_critical2 = -10.0 / 3.0;
double y1 = func(x1);
double y2 = func(x2);
double y_critical1 = func(x_critical1);
double y_critical2 = func(x_critical2);
// Íàéäåì íàèáîëüøåå çíà÷åíèå
double max_value = y1;
double max_x = x1;
if (y2 > max_value) {
max_value = y2;
max_x = x2;
}
if (y_critical1 > max_value) {
max_value = y_critical1;
max_x = x_critical1;
}
if (y_critical2 > max_value) {
max_value = y_critical2;
max_x = x_critical2;
}
// Âûâîä ðåøåíèÿ íà ýêðàí
char solutionText[500];
sprintf(solutionText, "Íàèáîëüøåå çíà÷åíèå ôóíêöèè = %.2f ïðè x = %.2f", max_value, max_x);
outtextxy(10, 50, solutionText);
// Ïîñòðîåíèå ãðàôèêà ôóíêöèè íà èíòåðâàëå [-5, -3.5]
setcolor(YELLOW);
// Íàéäåì ðàçìåðû ãðàôè÷åñêîãî îêíà
int width = getmaxx();
int height = getmaxy();
int graph_x_start = 50; // Ëåâûé êðàé ãðàôèêà
int graph_y_start = height / 2; // Ñðåäíÿÿ ëèíèÿ äëÿ îñè y
int graph_width = width - 100; // Øèðèíà ãðàôèêà
// Óñòàíîâèì ìàñøòàá ïî îñè X è Y
double x_scale = graph_width / (x2 - x1); // Ìàñøòàá ïî X
double y_scale = 30; // Ìàñøòàá ïî Y (çàâèñèò îò ôóíêöèè)
// Îòîáðàæàåì îñè
setcolor(WHITE);
line(graph_x_start, 0, graph_x_start, height); // Îñü Y
line(0, graph_y_start, width, graph_y_start); // Îñü X
// Ðàçìåòêà (ñåòêà)
setcolor(LIGHTGRAY);
// Ãîðèçîíòàëüíûå ëèíèè (ïî Y)
for (int i = -5; i <= 5; i++) {
int y_line_pos = graph_y_start - i * y_scale;
line(0, y_line_pos, width, y_line_pos);
char label[10];
sprintf(label, "%d", i);
outtextxy(graph_x_start - 30, y_line_pos - 5, label);
}
// Âåðòèêàëüíûå ëèíèè (ïî X)
for (double i = x1; i <= x2; i += 0.5) {
int x_line_pos = graph_x_start + (int)((i - x1) * x_scale);
line(x_line_pos, 0, x_line_pos, height);
char label[10];
sprintf(label, "%.1f", i);
outtextxy(x_line_pos - 10, graph_y_start + 10, label);
}
// Îòðèñîâêà ôóíêöèè
setcolor(YELLOW);
for (int i = graph_x_start; i < graph_x_start + graph_width; i++) {
double x = x1 + (i - graph_x_start) / x_scale;
double y = func(x);
int graph_y = graph_y_start - (int)(y * y_scale);
putpixel(i, graph_y, YELLOW);
}
// Îòìå÷àåì òî÷êó ìàêñèìóìà
int max_graph_x = graph_x_start + (int)((max_x - x1) * x_scale);
int max_graph_y = graph_y_start - (int)(max_value * y_scale);
setcolor(RED);
circle(max_graph_x, max_graph_y, 5);
outtextxy(max_graph_x + 10, max_graph_y - 10, "Max");
// Çàïèñü ðåøåíèÿ â ôàéë
FILE *file = fopen("Ðåøåíèå_çàäà÷è.txt", "w");
if (file == NULL) {
printf("Îøèáêà ïðè îòêðûòèè ôàéëà!\n");
return 1;
}
fprintf(file, "Íàèáîëüøåå çíà÷åíèå ôóíêöèè íà îòðåçêå [-5, -3.5]:\n");
fprintf(file, "Ìàêñèìóì = %.2f ïðè x = %.2f\n", max_value, max_x);
fclose(file);
printf("Îòâåò çàïèñàí â ôàéë 'Ðåøåíèå_çàäà÷è.txt'.\n");
// Îæèäàíèå ââîäà äëÿ çàêðûòèÿ ãðàôè÷åñêîãî îêíà
getch();
closegraph();
return 0;
}
Binary file not shown.
@@ -0,0 +1,95 @@
#include <graphics.h>
#include <conio.h>
#include <stdio.h>
#include <math.h>
// Функция для вычисления левой части уравнения: 4√3 * cos^3(x)
double left_side(double x) {
return 4 * sqrt(3) * pow(cos(x), 3);
}
// Функция для вычисления правой части уравнения: cos(2x + π/2)
double right_side(double x) {
return cos(2 * x + M_PI / 2);
}
int main() {
// Инициализация графического режима
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
// Заданный отрезок [-4π; -5π/2]
double x_start = -4 * M_PI;
double x_end = -5 * M_PI / 2;
// Массив для хранения корней
double roots[10];
int root_count = 0;
// Поиск корней уравнения на заданном отрезке с шагом 0.01
for (double x = x_start; x <= x_end; x += 0.01) {
double left = left_side(x);
double right = right_side(x);
// Проверяем условие совпадения левой и правой частей уравнения с некоторой погрешностью
if (fabs(left - right) < 0.01) {
roots[root_count] = x;
root_count++;
}
}
// Координаты для рисования графиков
int x_center = getmaxx() / 2;
int y_center = getmaxy() / 2;
// Рисуем оси
line(0, y_center, getmaxx(), y_center); // Ось X
line(x_center, 0, x_center, getmaxy()); // Ось Y
// Подписи для осей
outtextxy(x_center + 5, 5, "Y");
outtextxy(getmaxx() - 10, y_center + 5, "X");
// Рисуем графики левой и правой частей уравнения
for (double x = x_start; x <= x_end; x += 0.01) {
double left = left_side(x);
double right = right_side(x);
// Левую часть уравнения рисуем белым
putpixel(x_center + (int)(x * 100), y_center - (int)(left * 100), WHITE);
// Правую часть уравнения рисуем желтым
putpixel(x_center + (int)(x * 100), y_center - (int)(right * 100), YELLOW);
}
// Вывод текста с найденными корнями
setcolor(WHITE);
char root_text[100];
sprintf(root_text, "Найдено %d корней", root_count);
outtextxy(10, 10, root_text);
// Запись корней в файл
FILE *file = fopen("answer.txt", "w");
if (file == NULL) {
printf("Ошибка при открытии файла!\n");
return 1;
}
// Запись найденных корней в файл
fprintf(file, "Ответ задачи:\n");
fprintf(file, "Найдено %d корней:\n", root_count);
for (int i = 0; i < root_count; i++) {
fprintf(file, "x = %.5f\n", roots[i]);
}
// Закрытие файла
fclose(file);
printf("Ответ записан в файл 'answer.txt'.\n");
// Ожидание завершения
getch();
closegraph();
return 0;
}
@@ -0,0 +1,40 @@
#include <stdio.h>
int main() {
FILE *initialFile = fopen("1 input.txt", "w");
if (initialFile == NULL) {
printf("Не удалось создать файл 1 input.txt\n");
return 1;
}
fprintf(initialFile, "5 6 1 10 24\n");
fclose(initialFile);
FILE *inputFile = fopen("1 input.txt", "r");
if (inputFile == NULL) {
printf("Не удалось открыть файл 1 input.txt\n");
return 1;
}
FILE *outputFile = fopen("1 output.txt", "w");
if (outputFile == NULL) {
printf("Не удалось открыть файл 1 output.txt\n");
fclose(inputFile);
return 1;
}
float a, b, c, d, e;
fscanf(inputFile, "%f %f %f %f %f", &a, &b, &c, &d, &e);
fclose(inputFile);
float result = ((a / b) + (c / d)) * e;
fprintf(outputFile, "%.2f\n", result);
fclose(outputFile);
printf("output.txt\n");
return 0;
}
@@ -0,0 +1,38 @@
#include <graphics.h>
#include <iostream>
#include <fstream>
#include <vector>
void drawBarChart(const std::vector<int>& temperatures) {
int x = 50;
for (int temp : temperatures) {
bar(x, 400 - temp * 2, x + 30, 400);
x += 40;
}
}
std::vector<int> readTemperatures(const std::string& filename) {
std::ifstream file(filename);
std::vector<int> temperatures;
int temp;
while (file >> temp) {
temperatures.push_back(temp);
}
return temperatures;
}
int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
std::vector<int> temperatures = readTemperatures("temperatures.txt");
drawBarChart(temperatures);
getch();
closegraph();
return 0;
}
@@ -0,0 +1,23 @@
#include <graphics.h>
#include <iostream>
void plotInequality() {
for (int x = -10; x <= 10; x++) {
if (4 * x - x * x <= 0) {
putpixel(300 + x * 10, 300 - (4 * x - x * x) * 10, WHITE);
} else {
putpixel(300 + x * 10, 300 - (4 * x - x * x) * 10, WHITE);
}
}
}
int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
plotInequality();
getch();
closegraph();
return 0;
}
@@ -0,0 +1,49 @@
#include <iostream>
#include <cmath>
#include <graphics.h>
using namespace std;
int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
const int angleABD = 46;
const int angleCAD = 58;
int angleABC = 180 - angleABD - angleCAD;
setcolor(WHITE);
outtextxy(10, 10);
outtextxy(10, 30);
int x0 = 200, y0 = 200;
int radius = 100;
circle(x0, y0, radius);
int xA = x0 + radius * cos(angleCAD * M_PI / 180);
int yA = y0 - radius * sin(angleCAD * M_PI / 180);
int xB = x0 + radius * cos((angleCAD + angleABD) * M_PI / 180);
int yB = y0 - radius * sin((angleCAD + angleABD) * M_PI / 180);
int xC = x0 + radius * cos((angleCAD + angleABD + angleABC) * M_PI / 180);
int yC = y0 - radius * sin((angleCAD + angleABD + angleABC) * M_PI / 180);
int xD = x0 + radius * cos((angleCAD + angleABD + angleABC + angleCAD) * M_PI / 180);
int yD = y0 - radius * sin((angleCAD + angleABD + angleABC + angleCAD) * M_PI / 180);
putpixel(xA, yA, WHITE);
putpixel(xB, yB, WHITE);
putpixel(xC, yC, WHITE);
putpixel(xD, yD, WHITE);
line(xA, yA, xB, yB);
line(xB, yB, xC, yC);
line(xC, yC, xD, yD);
line(xD, yD, xA, yA);
char text[50];
sprintf(text, "Angle ABC = %d°", angleABC);
outtextxy(10, 50, text);
getch();
closegraph();
return 0;
}
@@ -0,0 +1,39 @@
#include <iostream>
#include <graphics.h>
#include <cmath>
using namespace std;
int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
const double distance = 208;
const double riverSpeed = 5;
const double timeDifference = 5;
double boatSpeed = (distance * (riverSpeed + distance / (timeDifference + distance / riverSpeed))) / (2 * distance);
int riverWidth = 50;
line(50, 200, 50 + riverWidth, 200);
line(50, 250, 50 + riverWidth, 250);
line(50, 200, 50, 250);
line(50 + riverWidth, 200, 50 + riverWidth, 250);
int boatSize = 20;
int boatX = 50 + riverWidth / 2 - boatSize / 2;
int boatY = 220;
rectangle(boatX, boatY, boatX + boatSize, boatY + boatSize / 2);
line(boatX + boatSize / 2, boatY + boatSize / 4, boatX + boatSize / 2 - 10, boatY + boatSize / 4 - 10);
line(boatX + boatSize / 2, boatY + boatSize / 4, boatX + boatSize / 2 - 10, boatY + boatSize / 4 + 10);
line(boatX + boatSize / 2, boatY + boatSize / 4, boatX + boatSize / 2 + 10, boatY + boatSize / 4 - 10);
line(boatX + boatSize / 2, boatY + boatSize / 4, boatX + boatSize / 2 + 10, boatY + boatSize / 4 + 10);
char text[50];
sprintf(text, "Boat speed: %.2f km/h", boatSpeed);
outtextxy(10, 70, text);
getch();
closegraph();
return 0;
}
@@ -0,0 +1,36 @@
#include <iostream>
#include <graphics.h>
#include <cmath>
using namespace std;
int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
line(100, 400, 400, 400);
line(100, 400, 100, 100);
const double k1 = 2, b1 = 1;
const double k2 = -1, b2 = 3;
const double k3 = 0.5, b3 = -2;
const double k4 = -3, b4 = -4;
for (int x = 100; x <= 400; x++) {
int y1 = k1 * (x - 100) + b1 + 400;
putpixel(x, y1, GREEN);
int y2 = k2 * (x - 100) + b2 + 400;
putpixel(x, y2, BLUE);
int y3 = k3 * (x - 100) + b3 + 400;
putpixel(x, y3, RED);
int y4 = k4 * (x - 100) + b4 + 400;
putpixel(x, y4, YELLOW);
}
getch();
closegraph();
return 0;
}
@@ -0,0 +1,24 @@
#include <iostream>
#include <graphics.h>
#include <cmath>
using namespace std;
int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
line(100, 400, 400, 400);
line(100, 400, 100, 100);
for (int x = 100; x <= 400; x++) {
double y = abs(x - 100) * (x - 100) / 100 + abs(x - 100) / 100 - 3 * (x - 100) / 100 + 400;
putpixel(x, y, GREEN);
}
getch();
closegraph();
return 0;
}
@@ -0,0 +1,48 @@
#include <iostream>
#include <graphics.h>
#include <cmath>
#include <fstream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
srand(time(0));
ofstream fileX("x.txt"), fileY("y.txt");
for (int i = 0; i < 100; i++) {
int x = rand() % 31 - 5;
int y = rand() % 31 - 5;
fileX << x << endl;
fileY << y << endl;
}
fileX.close();
fileY.close();
ifstream fileXRead("x.txt"), fileYRead("y.txt");
int x, y;
while (fileXRead >> x && fileYRead >> y) {
int graphX = x * 10 + 100;
int graphY = 400 - y * 10;
if (x + y == 35) {
circle(graphX, graphY, 5);
} else {
putpixel(graphX, graphY, WHITE);
}
}
fileXRead.close();
fileYRead.close();
getch();
closegraph();
return 0;
}
@@ -0,0 +1,178 @@
#include <stdio.h>
#include <stdlib.h>
int t19_a() {
FILE *fp;
int num, count_positive = 0, count_negative = 0;
int sum_positive = 0, sum_negative = 0;
float avg_positive = 0.0, avg_negative = 0.0;
fp = fopen("netext_a.bin", "rb"); // Îòêðûòèå áèíàðíîãî ôàéëà äëÿ ÷òåíèÿ
if (fp == NULL) {
printf("Îøèáêà îòêðûòèÿ ôàéëà!\n");
return 1;
}
while (fread(&num, sizeof(char), 1, fp) == 1) { // ×òåíèå ïî 1 öåëîìó ÷èñëó
if (num > 0) {
count_positive++;
sum_positive += num;
} else if (num < 0) {
count_negative++;
sum_negative += num;
}
}
fclose(fp); // Çàêðûòèå ôàéëà
if (count_positive > 0) {
avg_positive = (float)sum_positive / count_positive;
}
if (count_negative > 0) {
avg_negative = (float)sum_negative / count_negative;
}
printf("Number of positive numbers: %d\n", count_positive);
printf("Number of negative numbers: %d\n", count_negative);
printf("Sum of positive numbers: %d\n", sum_positive);
printf("Sum of negative numbers: %d\n", sum_negative);
printf("Arithmetic mean of positive numbers: %.2f\n", avg_positive);
printf("Arithmetic mean of negative numbers: %.2f\n", avg_negative);
return 0;
}
int t19_b() {
FILE *fp;
int num, count_positive = 0, count_negative = 0;
int sum_positive = 0, sum_negative = 0;
float avg_positive = 0.0, avg_negative = 0.0;
fp = fopen("netext_b.bin", "rb"); // Îòêðûòèå áèíàðíîãî ôàéëà äëÿ ÷òåíèÿ
if (fp == NULL) {
printf("Îøèáêà îòêðûòèÿ ôàéëà!\n");
return 1;
}
while (fread(&num, sizeof(short), 1, fp) == 1) { // ×òåíèå ïî 1 öåëîìó ÷èñëó
if (num > 0) {
count_positive++;
sum_positive += num;
} else if (num < 0) {
count_negative++;
sum_negative += num;
}
}
fclose(fp); // Çàêðûòèå ôàéëà
if (count_positive > 0) {
avg_positive = (float)sum_positive / count_positive;
}
if (count_negative > 0) {
avg_negative = (float)sum_negative / count_negative;
}
printf("Number of positive numbers: %d\n", count_positive);
printf("Number of negative numbers: %d\n", count_negative);
printf("Sum of positive numbers: %d\n", sum_positive);
printf("Sum of negative numbers: %d\n", sum_negative);
printf("Arithmetic mean of positive numbers: %.2f\n", avg_positive);
printf("Arithmetic mean of negative numbers: %.2f\n", avg_negative);
return 0;
}
int t19_v() {
FILE *fp;
int num, count_positive = 0, count_negative = 0;
int sum_positive = 0, sum_negative = 0;
float avg_positive = 0.0, avg_negative = 0.0;
fp = fopen("netext_v.bin", "rb"); // Îòêðûòèå áèíàðíîãî ôàéëà äëÿ ÷òåíèÿ
if (fp == NULL) {
printf("Îøèáêà îòêðûòèÿ ôàéëà!\n");
return 1;
}
while (fread(&num, sizeof(int), 1, fp) == 1) { // ×òåíèå ïî 1 öåëîìó ÷èñëó
if (num > 0) {
count_positive++;
sum_positive += num;
} else if (num < 0) {
count_negative++;
sum_negative += num;
}
}
fclose(fp); // Çàêðûòèå ôàéëà
if (count_positive > 0) {
avg_positive = (float)sum_positive / count_positive;
}
if (count_negative > 0) {
avg_negative = (float)sum_negative / count_negative;
}
printf("Number of positive numbers: %d\n", count_positive);
printf("Number of negative numbers: %d\n", count_negative);
printf("Sum of positive numbers: %d\n", sum_positive);
printf("Sum of negative numbers: %d\n", sum_negative);
printf("Arithmetic mean of positive numbers: %.2f\n", avg_positive);
printf("Arithmetic mean of negative numbers: %.2f\n", avg_negative);
return 0;
}
int t20() {
FILE *fp;
int num, count_positive = 0, count_negative = 0;
int sum_positive = 0, sum_negative = 0;
float avg_positive = 0.0, avg_negative = 0.0;
fp = fopen("netext2.bin", "rb"); // Îòêðûòèå áèíàðíîãî ôàéëà äëÿ ÷òåíèÿ
if (fp == NULL) {
printf("Îøèáêà îòêðûòèÿ ôàéëà!\n");
return 1;
}
while (fread(&num, sizeof(char), 1, fp) == 1) { // ×òåíèå ïî 1 öåëîìó ÷èñëó
if (num > 0) {
count_positive++;
sum_positive += num;
} else if (num < 0) {
count_negative++;
sum_negative += num;
}
}
fclose(fp); // Çàêðûòèå ôàéëà
if (count_positive > 0) {
avg_positive = (float)sum_positive / count_positive;
}
if (count_negative > 0) {
avg_negative = (float)sum_negative / count_negative;
}
printf("Number of positive numbers: %d\n", count_positive);
printf("Number of negative numbers: %d\n", count_negative);
printf("Sum of positive numbers: %d\n", sum_positive);
printf("Sum of negative numbers: %d\n", sum_negative);
printf("Arithmetic mean of positive numbers: %.2f\n", avg_positive);
printf("Arithmetic mean of negative numbers: %.2f\n", avg_negative);
return 0;
}
void main() {
printf("a\n");
t19_a();
printf("b\n");
t19_b();
printf("v\n");
t19_v();
printf("20\n");
t20();
}
@@ -0,0 +1,42 @@
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(NULL));
FILE *fn_a = fopen("netext_a.bin", "wb");
if (fn_a == NULL) {
perror("Error opening file netext_a.bin");
return 1;
}
for (int i = 1; i <= 100; i++) {
char n = -50 + rand() % 151;
fwrite(&n, sizeof(char), 1, fn_a);
}
fclose(fn_a);
FILE *fn_b = fopen("netext_b.bin", "wb");
if (fn_b == NULL) {
perror("Error opening file netext_b.bin");
return 1;
}
for (int i = 1; i <= 100; i++) {
char n = -50 + rand() % 151;
fwrite(&n, sizeof(char), 1, fn_b);
}
fclose(fn_b);
FILE *fn_v = fopen("netext_v.bin", "wb");
if (fn_v == NULL) {
perror("Error opening file netext_v.bin");
return 1;
}
for (int i = 1; i <= 100; i++) {
char n = -50 + rand() % 151;
fwrite(&n, sizeof(char), 1, fn_v);
}
fclose(fn_v);
return 0;
}
@@ -0,0 +1,44 @@
#include <stdio.h>
#include <math.h>
int main() {
FILE *initialFile = fopen("input.txt", "w");
if (initialFile == NULL) {
printf("Не удалось создать файл input.txt\n");
return 1;
}
fprintf(initialFile, "3 5 4 5 9\n");
fclose(initialFile);
FILE *inputFile = fopen("input.txt", "r");
if (inputFile == NULL) {
printf("Не удалось открыть файл input.txt\n");
return 1;
}
FILE *outputFile = fopen("output.txt", "w");
if (outputFile == NULL) {
printf("Не удалось открыть файл output.txt\n");
fclose(inputFile);
return 1;
}
float a, b, c, d, e;
fscanf(inputFile, "%f %f %f %f %f", &a, &b, &c, &d, &e);
fclose(inputFile);
float numerator = pow(a, 3) * pow(b, 5);
numerator = pow(numerator, c);
float denominator = pow(d, 5) * pow(e, 9);
float result = numerator / denominator;
fprintf(outputFile, "%.2f\n", result);
fclose(outputFile);
printf("Вычисления завершены, результат записан в output.txt\n");
return 0;
}
@@ -0,0 +1,14 @@
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
FILE *fn = fopen("netext2.bin", "wb");
float n;
for (int i = 1; i <= 100; i++) {
n = -49.99 + ((float)rand()/(float)RAND_MAX) * 101.98;
fwrite(&n, sizeof(float), 1, fn);
}
fclose(fn);
return 0;
}
@@ -0,0 +1,47 @@
#include <iostream>
#include <graphics.h>
using namespace std;
void drawGrid() {
for (int i = 0; i <= 600; i += 20) {
line(i, 0, i, 600);
line(0, i, 600, i);
}
}
int main() {
// Óñòàíîâêà ãðàôè÷åñêîãî ðåæèìà
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
drawGrid();
setcolor(12);
// Îñè êîîðäèíàò
line(200, 260, 400, 260); // îñü X
line(300, 360, 300, 160); // îñü Y
// line(320, 340, 400, 220);
// Ðèñîâàíèå ãðàôèêà
for (int x = 0; x <= 600; x++) {
float y = 1.25*x - 4.25; // Âû÷èñëåíèå y ïî ãðàôèêó
putpixel(580-x, (int)y, 2);
}
bar(0,0,500,100);
// Òåêñò óñëîâèÿ
setcolor(14);
outtextxy(10, 10, "a = y2 - y1 / x2 - x1 = 2 - (-3) / 5 - 1 = 2 + 3 / 5 - 1 = 5 / 4");
outtextxy(10,30, "-3 = 5 / 4 * 1 + b ---> -3 = 5 / 4 + b");
outtextxy(10,50, "b = -3 - 5 / 4 = -12 / 4 - 5 / 4 = -17 / 4");
// Òåêñò îòâåòà
outtextxy(10, 70, "Answer: f(11) = 1.25 * 11 - 4.25 = 9.5");
printf("a = y2 - y1 / x2 - x1 = 2 - (-3) / 5 - 1 = 2 + 3 / 5 - 1 = 5 / 4");
printf("-3 = 5 / 4 * 1 + b ---> -3 = 5 / 4 + b");
printf("b = -3 - 5 / 4 = -12 / 4 - 5 / 4 = -17 / 4");
printf("Answer: f(11) = 1.25 * 11 - 4.25 = 9.5");
getch();
closegraph();
return 0;
}
@@ -0,0 +1,77 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <graphics.h>
#include <winbgim.h>
#define MAX_PRODUCTS 100
#define MAX_NAME_LEN 50
int main() {
FILE *initialFile = fopen("Данные.txt", "w");
if (initialFile == NULL) {
printf("Не удалось создать файл Данные.txt\n");
return 1;
}
fprintf(initialFile, "Продукт1 14.0 17.0 12.0 20.0\n");
fclose(initialFile);
FILE *file = fopen("Данные.txt", "r");
if (file == NULL) {
printf("Не удалось открыть файл Данные.txt\n");
return 1;
}
char products[MAX_PRODUCTS][MAX_NAME_LEN];
float proteins[MAX_PRODUCTS], fats[MAX_PRODUCTS], carbohydrates[MAX_PRODUCTS], other[MAX_PRODUCTS];
int count = 0;
while (fscanf(file, "%s %f %f %f %f", products[count], &proteins[count], &fats[count], &carbohydrates[count], &other[count]) == 5) {
count++;
}
fclose(file);
int gd = DETECT, gm;
initwindow(640, 480, "Круговая диаграмма");
for (int i = 0; i < count; i++) {
cleardevice();
setcolor(WHITE);
setlinestyle(SOLID_LINE, 0, 3); // ширина линий на 3 пикселя
outtextxy(200, 20, products[i]);
float total = proteins[i] + fats[i] + carbohydrates[i] + other[i];
float start_angle = 0;
// Белки
setcolor(RED);
float sweep_angle = (proteins[i] / total) * 360;
fillellipse(320, 240, 150, 150);
pieslice(320, 240, start_angle, start_angle + sweep_angle, 150);
start_angle += sweep_angle;
// Жиры
setcolor(BLUE);
sweep_angle = (fats[i] / total) * 360;
pieslice(320, 240, start_angle, start_angle + sweep_angle, 150);
start_angle += sweep_angle;
// Углеводы
setcolor(GREEN);
sweep_angle = (carbohydrates[i] / total) * 360;
pieslice(320, 240, start_angle, start_angle + sweep_angle, 150);
start_angle += sweep_angle;
// Прочее
setcolor(YELLOW);
sweep_angle = (other[i] / total) * 360;
pieslice(320, 240, start_angle, start_angle + sweep_angle, 150);
getch();
}
closegraph();
printf("Круговая диаграмма отображена на экране\n");
return 0;
}
@@ -0,0 +1,62 @@
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <graphics.h>
#include <winbgim.h>
#define MAX_VARIANTS 4
int main() {
FILE *initialFile = fopen("function_data.txt", "w");
if (initialFile == NULL) {
printf("Не удалось создать файл function_data.txt\n");
return 1;
}
fprintf(initialFile, "13 15\n-13 15\n13 -15\n-13 -15\n");
fclose(initialFile);
FILE *file = fopen("function_data.txt", "r");
if (file == NULL) {
printf("Не удалось открыть файл function_data.txt\n");
return 1;
}
float a[MAX_VARIANTS], c[MAX_VARIANTS];
int count = 0;
// Чтение данных из файла
while (fscanf(file, "%f %f", &a[count], &c[count]) == 2) {
count++;
}
fclose(file);
// Инициализация графического режима с использованием winbgim
int gd = DETECT, gm;
initwindow(640, 480, "Графики функции");
// Построение графиков для каждого варианта
for (int i = 0; i < count; i++) {
cleardevice();
setcolor(WHITE);
line(320, 0, 320, 480); // Ось Y
line(0, 240, 640, 240); // Ось X
setcolor(RED);
for (int x = -320; x <= 320; x++) {
int graphX = x + 320;
float y = a[i] * (x / 20.0) * (x / 20.0) + 20 * (x / 20.0) + c[i];
int graphY = 240 - (int)(y * 20);
if (graphY >= 0 && graphY <= 480) {
putpixel(graphX, graphY, RED);
}
}
delay(2000); // Задержка для отображения графика
}
closegraph();
printf("Графики отображены на экране\n");
return 0;
}
@@ -0,0 +1,38 @@
#include <graphics.h>
#include <iostream>
#include <fstream>
void drawTriangle(float A[], float B[], float C[]) {
line(A[0], A[1], B[0], B[1]);
line(B[0], B[1], C[0], C[1]);
line(C[0], C[1], A[0], A[1]);
}
float calculateArea(float base, float height) {
return 0.5 * base * height;
}
int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
// Условия задачи
float A[] = {100, 100}, B[] = {200, 300}, C[] = {300, 100};
drawTriangle(A, B, C);
// Параметры
float AC = 16, MN = 10, areaABC = 32;
// Площадь треугольника MBN
float areaMBN = (MN / AC) * areaABC;
outtextxy(10, 10, "Area of triangle MBN:");
char buffer[50];
sprintf(buffer, "%.2f", areaMBN);
outtextxy(10, 30, buffer);
getch();
closegraph();
return 0;
}
@@ -0,0 +1,34 @@
#include <graphics.h>
#include <iostream>
void drawGrid() {
for (int i = 0; i <= 600; i += 20) {
line(i, 0, i, 600);
line(0, i, 600, i);
}
}
void drawParallelogram() {
int x[] = {100, 200, 100, 100, 250, 100, 200, 200, 100, 200}; // êîîðäèíàòû âåðøèí
// int y[] = {100, 100, 200, 200};
setcolor(RED);
drawpoly(4, x); // Ïåðåäàåì ìàññèâ òî÷åê
}
int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
drawGrid();
drawParallelogram();
// Ïëîùàäü ïàðàëëåëîãðàììà
int base = 150; // äëèíà îñíîâàíèÿ (ðàññ÷èòàííàÿ ïî êîîðäèíàòàì)
int height = 100; // âûñîòà (ðàññ÷èòàííàÿ ïî êîîðäèíàòàì)
float area = base * height;
std::cout << "Area of the parallelogram: " << area << std::endl;
getch(); // Îæèäàíèå ââîäà
closegraph();
return 0;
}
@@ -0,0 +1,34 @@
#include <graphics.h>
#include <math.h>
void drawGraph() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
int x, y;
int max_x = getmaxx();
int max_y = getmaxy();
int origin_x = max_x / 2;
int origin_y = max_y / 2;
// Draw axes
line(0, origin_y, max_x, origin_y); // X-axis
line(origin_x, 0, origin_x, max_y); // Y-axis
// Plot the function
for (x = -origin_x; x <= origin_x; x++) {
float fx = (float)x / 10; // Scale x for better visibility
float fy = ((fx + 4) * (fx * fx + 3 * fx + 2)) / (fx + 1);
y = origin_y - (int)(fy * 10); // Scale y for better visibility
putpixel(origin_x + x, y, GREEN);
}
getch();
closegraph();
}
int main() {
drawGraph();
return 0;
}
@@ -0,0 +1,51 @@
#include <iostream>
#include <cmath>
#include <graphics.h>
using namespace std;
int main() {
// Установка графического режима
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
// Параметры задачи
const double a = 11; // Меньшая сторона треугольника
const double k1 = 6, k2 = 7, k3 = 23; // Отношения дуг
// Вычисление углов треугольника
double alpha = (k1 / (k1 + k2 + k3)) * 360;
double beta = (k2 / (k1 + k2 + k3)) * 360;
double gamma = (k3 / (k1 + k2 + k3)) * 360;
// Вычисление радиуса описанной окружности
double R = a / (2 * sin(gamma * M_PI / 180));
// Вывод условия задачи в графическом виде
setcolor(WHITE);
outtextxy(10, 10, "Вершины треугольника делят описанную около него окружность");
outtextxy(10, 30, "на три дуги, длины которых относятся, как 6:7:23.");
outtextxy(10, 50, "Найти радиус окружности, если меньшая из сторон треугольника равна 11.");
// Рисование треугольника
int x0 = 200, y0 = 200;
int x1 = x0 + a / 2, y1 = y0 + a * sqrt(3) / 2;
int x2 = x0 - a / 2, y2 = y0 + a * sqrt(3) / 2;
line(x0, y0, x1, y1);
line(x1, y1, x2, y2);
line(x2, y2, x0, y0);
// Рисование описанной окружности
circle(x0, y0+6, R*1.2);
// Вывод ответа
char text[50];
sprintf(text, "Радиус окружности: %.2f", R);
outtextxy(10, 70, text);
getch();
closegraph();
return 0;
}
@@ -0,0 +1,51 @@
#include <iostream>
#include <cmath>
#include <graphics.h>
using namespace std;
int main() {
// Установка графического режима
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
// Параметры задачи
const double AB = 16; // Боковая сторона AB
const double CD = 34; // Боковая сторона CD
const double BC = 2; // Основание BC
// Вычисление высоты трапеции
double h = AB / 2; // Высота равна половине боковой стороны AB
// Вычисление площади трапеции
double S = (AB + CD) * h / 2;
// Вывод условия задачи в графическом виде
setcolor(WHITE);
outtextxy(10, 10, "Боковые стороны AB и CD трапеции ABCD равны соответственно 16 и 34, а основание BC равно 2.");
outtextxy(10, 30, "Биссектриса угла ADC проходит через середину стороны AB. Найти площадь трапеции.");
// Рисование трапеции
int x0 = 100, y0 = 300; // Вершина A
int x1 = x0 + AB, y1 = y0; // Вершина B
int x2 = x1 - BC, y2 = y0 - h; // Вершина C
int x3 = x2 - (CD - AB), y3 = y2; // Вершина D
line(x0, y0, x1, y1);
line(x1, y1, x2, y2);
line(x2, y2, x3, y3);
line(x3, y3, x0, y0);
// Рисование биссектрисы
line(x3, y3, x0 + AB / 2, y0);
// Вывод ответа
char text[50];
sprintf(text, "Площадь трапеции: %.2f", S);
outtextxy(10, 50, text);
getch();
closegraph();
return 0;
}
@@ -0,0 +1,36 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<CodeBlocks_project_file>
<FileVersion major="1" minor="6" />
<Project>
<Option title="С(2024)" />
<Option pch_mode="2" />
<Option compiler="gcc" />
<Build>
<Target title="Debug">
<Option output="bin/Debug/С(2024)" prefix_auto="1" extension_auto="1" />
<Option object_output="obj/Debug/" />
<Option type="1" />
<Option compiler="gcc" />
<Compiler>
<Add option="-g" />
</Compiler>
</Target>
<Target title="Release">
<Option output="bin/Release/С(2024)" prefix_auto="1" extension_auto="1" />
<Option object_output="obj/Release/" />
<Option type="1" />
<Option compiler="gcc" />
<Compiler>
<Add option="-O2" />
</Compiler>
<Linker>
<Add option="-s" />
</Linker>
</Target>
</Build>
<Compiler>
<Add option="-Wall" />
</Compiler>
<Extensions />
</Project>
</CodeBlocks_project_file>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<CodeBlocks_layout_file>
<FileVersion major="1" minor="0" />
<ActiveTarget name="Release" />
</CodeBlocks_layout_file>