Search code examples
c++iomanip

Remove number demical and turn into hexadecimal


#include <iostream>
#include <iomanip> 
using namespace std;

int main() {
    int T; cin >> T;
    cout << setiosflags(ios::uppercase);
    cout << setw(0xf) << internal;
    while (T--) {
        double A; cin >> A;
        double B; cin >> B;
        double C; cin >> C;

        cout << fixed << setprecision(0) << hex << showbase << A << '\n';
        cout << fixed << setprecision(2) << showpos << right << setfill('_') << setw(15) << B << '\n';
        cout << fixed << setprecision(9) << scientific << C;

    }
    return 0;

}

This is the problems that I can't solve:

  • I want to turn number A into a hexadecimal number (including the 0x prefix) and remove its decimal.

    Ex: A = 1345.6454 => I just take 1345 and remove 6454.

  • In the output of the above code, number C displays a + sign and I want to remove it.

Does someone know how to solve these problems?


Solution

  • Per https://en.cppreference.com/w/cpp/io/manip/fixed:

    Hexadecimal floating-point formatting ignores the stream precision specification, as required by the specification of std::num_put::do_put.

    To truncate the decimal off of a floating-point number, cast the value to an integer, eg:

    cout << hex << showbase << static_cast<int>(A) << '\n';
    

    Per https://en.cppreference.com/w/cpp/locale/num_put/put:

    For both integer and floating-point types, if showpos is set, the modifier + is prepended

    And per https://en.cppreference.com/w/cpp/io/c/fprintf:

    +: the sign of signed conversions is always prepended to the result of the conversion (by default the result is preceded by minus only when it is negative)

    You have enabled showpos when printing B, and it is still enabled when printing C.

    You can use std::resetiosflags(std::ios::showpos) or std::noshowpos to disable showpos:

    cout << resetiosflags(ios::showpos) << fixed << setprecision(9) << scientific << C;
    
    cout << noshowpos << fixed << setprecision(9) << scientific << C;