cpp / beginner
Snippet
Typumwandlung: Zwischen Typen konvertieren
Typumwandlung konvertiert einen Wert von einem Datentyp in einen anderen. Explizite Umwandlung mit (typ)wert erzwingt die Konvertierung. Bei Division von Integern ist das Ergebnis eine Ganzzahl-Division (schneidet Dezimalstellen ab). Umwandlung eines Operanden in double stellt Gleitkomma-Division sicher. Dies ist essentiell um zu kontrollieren, wie C++ deine Werte interpretiert.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>using namespace std;int main() {int whole = 10;int other = 3;double result1 = whole / other;double result2 = (double)whole / other;cout << "Ganzzahl-Division: " << result1 << endl;cout << "Mit Casting: " << result2 << endl;char letter = 'A';int ascii = (int)letter;cout << "Buchstabe 'A' als Zahl: " << ascii << endl;double pi = 3.14159;int truncated = (int)pi;cout << "Gerundet: " << truncated << endl;return 0;}
Erklärung
1
double result1 = whole / other;
Ganzzahl-Division: 10 / 3 = 3 (Dezimalteil verloren)
2
(double)whole / other
Wandelt 'whole' vor der Division in double um, Ergebnis ist 3.333...
3
(int)letter
Konvertiert Zeichen 'A' in seinen ASCII-Zahlenwert 65
4
(int)pi
Wandelt double in int um, kürzt Dezimalanteil (3.14159 wird zu 3)