Kursinhalt
C# Über die Grundlagen Hinaus
C# Über die Grundlagen Hinaus
3. Einführung in die Objektorientierte Programmierung (OOP)
Konstruktoren Üben
Das folgende Programm hat zwei Strukturen, eine davon heißt Point
, die eine Koordinate definiert, da sie ein x
und ein y
Attribut / Feld hat. Die andere Struktur heißt Triangle
und besteht aus 3 Punktobjekten. Im Konstruktor übergeben wir drei Punktobjekte, um ein Dreieck korrekt zu initialisieren.
Füllen Sie die Lücken aus, um die Konstruktoren beider Strukturen zu vervollständigen.
Es wird auch eine gute Übung zum Lesen von Code sein, den gesamten Code zu lesen und zu versuchen, ihn zu verstehen, es ist jedoch nicht notwendig, um diese Aufgabe zu lösen.
index
using System; class Program { struct Point { public double x; public double y; ___ { ___ = x; ___ = y; } } struct Triangle { public Point[] vertices; ___ { ___ = new Point[] { a, b, c }; } // Calculates and returns the area of the triangle based on the vertices. public double getArea() { // Storing the values in shorter variables for ease of use and code readability. double x1 = this.vertices[0].x; double x2 = this.vertices[1].x; double x3 = this.vertices[2].x; double y1 = this.vertices[0].y; double y2 = this.vertices[1].y; double y3 = this.vertices[2].y; // Calculating and returning the area of the triangle. // This formula is easy available on the internet, you don't need to understand it. return (0.5) * ( x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2) ); } } static void Main(string[] args) { Point p1 = new Point(47, 17); Point p2 = new Point(9, 50); Point p3 = new Point(7, 14); Triangle tri = new Triangle(p1, p2, p3); Console.WriteLine(tri.getArea()); } }
War alles klar?
Danke für Ihr Feedback!
Abschnitt 2. Kapitel 9