Java :: Aufgabe #290

1 Lösung Lösung öffentlich

Mathematische Vektoroperationen

Anfänger - Java von thunderbird - 28.04.2020 um 21:51 Uhr
Erstellen Sie ein Programm/ eine Funktion, mit der Vektorberechnungen durchgeführt werden können.
"Vektor" soll eine eigens erstellte Klasse sein, die aus 3 Fließkommazahlen bestehen.
Zudem beinhaltet die Klasse "Vektor" eine Methode zur Skalarmultiplikation, Addition, Subtraktion, Division und um das Kreuzprodukt zu berrechnen.
Erstellen Sie zur Darstellung eine Ausgabemethode.

Hinweis:
- Anstatt neue Methoden zu erstellen, können (sofern möglich) bereits vorhandene überladen werden.
- Mathematische Rechenregeln unter: https://de.wikipedia.org/wiki/Vektor

Lösungen:

vote_ok
von daniel91 (150 Punkte) - 28.05.2020 um 23:08 Uhr
Quellcode ausblenden Java-Code
// Klasse Vektor
class Vektor{
	
	// Objektvariablen
	private int x;
	private int y;
	private int z;
	
	// Konstruktor
	public Vektor(int _x, int _y, int _z) {
		x = _x;
		y = _y;
		z = _z;
	}
	
	// Klassenmethoden
	// - Addition
	public Vektor add(Vektor a){
		Vektor b = new Vektor(x, y, z);
		b.x = x + a.x;
		b.y = y + a.y;
		b.z = z + a.z;
		return b;
	}
	
	// - Subtraktion
	public Vektor sub(Vektor a){
		Vektor b = new Vektor(x, y, z);
		b.x = x - a.x;
		b.y = y - a.y;
		b.z = z - a.z;
		return b;
	}
	
	// - Kreuzprodukt
	public Vektor kreuz(Vektor a) {
		Vektor b = new Vektor(x, y, z);
		b.x = y*a.z - z*a.y;
		b.y = z*a.x - x*a.z;
		b.z = x*a.y - y*a.x;
		return b;
	}
	
	// - Skalarprodukt
	public int skal(Vektor a) {
		int c = x*a.x + y*a.y + z*a.z;
		return c;
	}
	
	// - Ausgabe
	public void ausgabe() {
		System.out.println("(" + this.x + ", " + this.y + ", " + this.z + ")");
	}
}

// Hauptklasse
public class Main {

	public static void main(String[] args) {
		
		// Zwei beliebige Vektoren erzeugen
		Vektor a = new Vektor(3, 1, 5);
		Vektor b = new Vektor(2, 2, 2);
		
		// Vektoren a und b ausgeben
		System.out.println("a =");
		a.ausgabe();
		System.out.println();
		System.out.println("b =");
		b.ausgabe();
		
		// Vektoren addieren und ausgeben
		System.out.println();
		System.out.println("a+b =");
		a.add(b).ausgabe();
		
		// Vektoren subtrahieren und ausgeben
		System.out.println();
		System.out.println("a-b =");
		a.sub(b).ausgabe();
		
		// Kreuzprodukt berechnen und ausgeben
		System.out.println();
		System.out.println("axb =");
		a.kreuz(b).ausgabe();
		
		// Skalarprodukt berechnen und ausgeben
		System.out.println();
		System.out.println("a*b =");
		System.out.println(a.skal(b));
	}
}
1800411

Du scheinst einen AdBlocker zu nutzen. Ich würde mich freuen, wenn du ihn auf dieser Seite deaktivierst und dich davon überzeugst, dass die Werbung hier nicht störend ist.