6

C++ の小数点の後ろに少なくとも 1 つの数値を含む数値をプログラムに出力させるにはどうすればよいですか? 出力: 1 = 1.0 または 1.25 = 1.25 または 2.2 = 2.2 または 3.456789 = 3.456789

前もって感謝します

4

4 に答える 4

5

showpoint小数点を強制的に出力するために使用します

double x = 1.0;
std::cout << std::showpoint << x << "\n";

0その後に、ストリームの精度を満たすために必要な数が続きます。

于 2013-09-05T21:22:13.533 に答える
3
#include <cmath>
#include <iostream>
#include <limits>

struct FormatFloat
{
    static constexpr const double precision = std::sqrt(std::numeric_limits<double>::epsilon());
    const double value;
    FormatFloat(double value) : value(value) {}
    void write(std::ostream& stream) const {
        std::streamsize n = 0;
        double f = std::abs(value - (long long)value);
        while(precision < f) {
            f *= 10;
            f -= (long long)f;
            ++n;
        }
        if( ! n) n = 1;
        n = stream.precision(n);
        std::ios_base::fmtflags flags = stream.setf(
            std::ios_base::fixed,
            std::ios_base::floatfield);
        stream << value;
        stream.flags(flags);
        stream.precision(n);
    }
};

inline std::ostream& operator << (std::ostream& stream, const FormatFloat& value) {
    value.write(stream);
    return stream;
}

inline FormatFloat format_float(double value) {
    return FormatFloat(value);
}

int main()
{
    std::cout
        << format_float(1) << '\n'
        << format_float(1.25) << '\n'
        << format_float(2.2) << '\n'
        << format_float(3.456789) << std::endl;
    return 0;
}
于 2013-09-06T07:39:55.970 に答える
1

この関数を頻繁に呼び出す場合、これは最適な方法ではないため、探しているものではない可能性がありますが、機能します。

次のようなもの:

string text = to_string(55);
if (text.find(".") != std::string::npos) {
    cout << "No digit added after decimal point" << text;
}
else
{
    cout << "Digit added after decimal point" << text << ".0";
}
于 2013-09-05T21:03:46.620 に答える
0
double value = ...;
std::ostringstream ss;
ss.precision(std::numeric_limits<double>::digits10 + 2);
ss << value;
std::string s = ss.str();
if (s.find('.') == string::npos)
{
    s.append(".0");
}

また

double value = ...;
std::wostringstream ss;
ss.precision(std::numeric_limits<double>::digits10 + 2);
ss << value;
std::wstring s = ss.str();
if (s.find(L'.') == string::npos)
{
    s.append(L".0");
}
于 2013-10-28T09:23:41.987 に答える