Informatics3-2024/Solutions2
A MathWikiből
Tartalomjegyzék |
Solutions
Only the solutions we discussed on the practical will be here. All the other tasks are perfect to practice for the written exam.
Distance
#include<stdio.h> #include<math.h> // need this for sqrt struct point2 { // our struct type float x; float y; }; // we need 2 points to calculate their distance // root of ((x1-x2)^2 + (y1-y2)^2) float distance(struct point2 a, struct point2 b) { // don't need to separate the calculation into smaller parts, you can do it in one line as well float x_part = a.x - b.x; // x1 - x2 float y_part = a.y - b.y; // y1 - y2 float sum = x_part * x_part + y_part * y_part; return sqrt(sum); } // testing here int main(void) { struct point2 p1; struct point2 p2; p1.x = 1; p1.y = 1; p2.x = 2; p2.y = 2; printf("%f\n", distance(p1, p2)); return 0; }
Min-max
#include<stdio.h> void swap(int *min, int *max) { // 2 pointer parameters if (*min > *max) { // do we need to swap? int temp; // temporary variable temp = *min; *min = *max; *max = temp; } } // just testing here int main(void) { int a = 5; int b = 7; int c = 9; printf("%d, %d, %d\n", a, b, c); swap(&a, &b); swap(&c, &a); printf("%d, %d, %d\n", a, b, c); return 0; }
Sort
#include<stdio.h> void swap(int *min, int *max) { // previous task if (*min > *max) { int temp; temp = *min; *min = *max; *max = temp; } } void sort(int a[], int n) { // bubble sorting an array int i, j; // cycle variables // two cycles needed // check what happens if you remove one of them for(j = 0; j < n-1; j++) { for(i = 0; i < n-1; i++) { swap(&a[i], &a[i+1]); // we swap if needed //printf("%d, %d\n", a[i], a[i+1]); //for testing } } } int main(void) { int a[] = {5, 4, 8, 2}; // creating the test array int i; // cycle variable for(i = 0; i < 4; i++) { printf("%d ", a[i]); // printing the initial array } sort(a, 4); // calling the function we're testing printf("\nsorting done\n"); for(i = 0; i < 4; i++) { printf("%d ", a[i]); // printing the sorted array } printf("\n"); return 0; }