Ausgabeformatierung von double bzw. float

In C++ gibt es mehrere Möglichkeiten, die Formatierung von Ausgaben mit cout zu steuern. Hier sind einige wichtige Formatierungsmanipulatoren, die häufig verwendet werden:

1. fixed und scientific

2. setprecision(int n)

3. setw(int n)

4. setfill(char c)

5. boolalpha und noboolalpha

Beispiel

Hier ist ein Beispiel, das einige dieser Formatierungsoptionen verwendet.

#include <iostream>
#include <iomanip> // für die Formatierungsmanipulatoren
 
using namespace std;
 
int main() {
    double number = 123.456;
 
    // Standardausgabe
    cout << "Standardausgabe: " << number << endl;
 
    // Feste Punktdarstellung mit 2 Dezimalstellen
    cout << fixed << setprecision(2);
    cout << "Feste Punktdarstellung: " << number << endl;
 
    // Wissenschaftliche Darstellung
    cout << scientific << setprecision(2);
    cout << "Wissenschaftliche Darstellung: " << number << endl;
 
    // Breitenformatierung
    cout << setw(10) << fixed << setprecision(2) << number << endl;
 
    // Auffüllzeichen
    cout << setfill('0') << setw(10) << fixed << setprecision(2) << number << endl;
 
    // Bool-Ausgabe
    bool flag = true;
    cout << boolalpha << "Bool-Wert: " << flag << endl;
    cout << noboolalpha << "Bool-Wert: " << flag << endl;
 
    return 0;
}

Fazit

Diese Formatierungsmanipulatoren bieten eine breite Palette an Optionen zur Steuerung der Ausgabe in C++. Je nach Anwendungsfall können sie verwendet werden, um die Lesbarkeit und Klarheit der Ausgaben zu verbessern.