C++ Kurs

Wenn fertig, bitte Fenster schließen

Lösung zur Lektion "Funktionen"


// Lösung zu Funktionen

// Dateien einbinden

#include <iostream>
#include <iomanip>
#include <cmath>

using std::cout;
using std::endl;

// Gravitationskonstante
const double GRAVITATION = 9.81;
// Konstante für Umrechnung Grad->Rad
const double PI2R = 2.0*3.1416;

// Funktionsdeklarationen
double Width(unsigned long velocity, short angle);
double Height(unsigned long velocity, short angle);

// main() Funktion
int main()
{
   // Variablen für Abwurfgeschw. und -winkel definieren
   unsigned long actVelocity;
   short    angle;

   // Anzahl der Nachkommastellen auf 2 begrenzen (entspr. cm)
   cout << std::fixed << std::setprecision(2);

   // Wurfdaten bei konst. Abwurfwinkel 45 Grad berechnen
   angle = 45;
   cout << "Schräger Wurf mit konst. Winkel von " << angle << " Grad\n";
   // Abwurfgeschwindigkeit variieren
   for (actVelocity=10; actVelocity<=20; actVelocity+=2)
   {
      cout << "Abwurfgeschw. (m/s):" << actVelocity;
      cout << ", Wurfweit (m):" << std::setw(5) << Width(actVelocity, angle);
      cout << ", Höhe (m):" << std::setw(5) << Height(actVelocity, angle) << endl;
   }

   // Wurfdaten bei konst. Abwurfgeschw. 28 m/s berechnen
   actVelocity = 28;
   cout << "\nSchräger Wurf mit konst. Abwurfgeschw. " << actVelocity << " m/s\n";
   // Wurfwinkel variieren
   for (angle=30; angle<=60; angle+=5)
   {
      cout << "Abwurfwinkel (Grad):" << angle;
      cout << ", Wurfweit (m):" << std::setw(5) << Width(actVelocity, angle);
      cout << ", Höhe (m):" << std::setw(5) << Height(actVelocity, angle) << endl;
   }
}

// Berechnung der Weite eines schrägen Wurfs
// velocity : Abwurfgeschwindigkeit (m/s)
// angle : Abwurfwinkel (Grad)
// Rückgabe: Weite (m)

double Width(unsigned long velocity, short angle)
{
   // Grad in Rad konvertieren für Sinus-Funktion
   double dfRad = angle/360.0*PI2R;
   // Weite berechnen und zurückliefern
   double dfWeite = velocity*velocity*sin(dfRad*2.0)/GRAVITATION;
   return dfWeite;
}

// Berechnung der max. Höhe eines schrägen Wurfs
// velocity : Abwurfgeschwindigkeit (m/s)
// angle : Abwurfwinkel (Grad)
// Rückgabe: max. Höhe (m)

double Height(unsigned long velocity, short angle)
{
   // Grad in Rad konvertieren für Sinus-Funktion
   double dfRad = angle/360.*PI2R;
   // Sinus nur einmal berechnen, wird 2-mal in Formel benötigt
   double dfSin = sin(dfRad);
   // max. Höhe berechnen und zurückliefern
   double dfHoehe = velocity*velocity * dfSin*dfSin/(2.0*GRAVITATION);
   return dfHoehe;
}