Informatics3-2024/Solutions4

A MathWikiből
(Változatok közti eltérés)
Kkovacs (vitalap | szerkesztései)
(Új oldal, tartalma: „== Solutions == Only the solutions we discussed on the practical will be here. All the other tasks are perfect to practice for the written exam. ==== Centroid (from t…”)

A lap jelenlegi, 2024. április 10., 19:07-kori változata

Solutions

Only the solutions we discussed on the practical will be here. All the other tasks are perfect to practice for the written exam.

Centroid (from the previous practical)

#include<iostream>
using namespace std;
 
float avg(float t[], int n) {
  float s = 0.0;
  for(int i = 0; i < n; i++) {
    s += t[i];
  }
  return s / n;
}
 
int main(void) {
  float x[10];
  float y[10];
  float z[10];
  cin >> x[0];
  cin >> y[0];
  cin >> z[0];
  int i = 0;
  while(x[i] != 0 || y[i] != 0 || z[i] != 0) {
    i++;
    cin >> x[i];
    cin >> y[i];
    cin >> z[i];
  }
  cout << "(" << avg(x, i) << ", " << avg(y, i) << ", " << avg(z, i) << ")" << endl;
 
  return 0;
}

Second step:

#include<iostream>
using namespace std;
 
float avg(float t[], int n) {
  float s = 0.0;
  for(int i = 0; i < n; i++) {
    s += t[i];
  }
  return s / n;
}
 
int main(void) {
  float *x;
  float *y;
  float *z;
  int n;
  cin >> n;
  x = new float[n];
  y = new float[n];
  z = new float[n];
  for(int i = 0; i < n; i++) {
    cin >> x[i];
    cin >> y[i];
    cin >> z[i];
  }
  cout << "(" << avg(x, n) << ", " << avg(y, n) << ", " << avg(z, n) << ")" << endl;
 
  delete[] x;
  delete[] y;
  delete[] z;
 
  return 0;
}

String slice

#include<iostream>
 
using namespace std;
 
char* slice(char* str, int n, int m) {
  int size = m - n + 2;
 
  char* retval = new char[size];
  for(int i = 0; i < size; i++) {
    retval[i] = str[i + n];
  }
 
  retval[size - 1] = '\0';
 
  return retval;
}
 
int main(void) {
 
  char c[] = "batman";
  char* s = slice(c, 1, 4);
 
  cout << s << endl;
 
  delete[] s;
 
  return 0;
}
Személyes eszközök