3

結果が整数の場合、小数点を出力しません。

結果が浮動小数点数の場合、末尾のゼロを出力しません。

cまたはでそれを行う方法c++

double result;
/*some operations on result */
printf("%g", result);

上記のアプローチは正しいですか?私の状況では正しい答えが得られません。

4

6 に答える 6

4

を使用snprintfして double 値を char 配列に出力し、最後から先頭まで「0」を「\0」に置き換えます。最後にゼロを末尾に付けずに数値を取得します。これが私の簡単なコードです。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void
remove_zeroes(double number, char * result, int buf_len)
{ 
    char * pos;
    int len;

    snprintf(result, buf_len, "%lf", number);
    len = strlen(result);

    pos = result + len - 1;
 #if 0
/* according to Jon Cage suggestion, removing this part */
    while(*div != '.')
        div++;
#endif
    while(*pos == '0')
        *pos-- = '\0';

    if(*pos == '.')
        *pos = '\0';

}

int
main(void)
{
    double a;
    char test[81];

    a = 10.1;

    printf("before it is %lf\n", a);
    remove_zeroes(a, test, 81);
    printf("after it is %s\n", test);

    a = 100;
    printf("before it is %lf\n", a);
    remove_zeroes(a, test, 81);
    printf("after it is %s\n", test);


    return 0;
}

そして出力は

before it is 10.100000
after it is 10.1
before it is 100.000000
after it is 100
于 2012-06-15T12:03:33.087 に答える
2

私は読みやすいコードを好みます。これは機能し、理解しやすいでしょう。ただし、ブーストが必要です。

#include <boost/algorithm/string.hpp>

std::string value = std::to_string((double)12); //yields 12.000000
boost::trim_right_if(value, boost::is_any_of("0")); //turn 12.000000 -> 12.
boost::trim_right_if(value, boost::is_any_of(".")); //turn 12. -> 12

以下のコードは 12 では機能しますが、120 または 0 では機能しないことに注意してください。小数点のすぐ左にあるゼロを削除しないように、2 つのステップをトリムする必要があります。したがって、行を保存しようとしないでください。

std::string value = std::to_string((double)120);
boost::trim_right_if(value, boost::is_any_of("0.")); //yields 12 not 120

コメントで、6桁の精度では不十分かもしれないと指摘されました。次に、これを試してください:

#include <iostream>
#include <sstream>
#include <iomanip>
#include <boost/algorithm/string.hpp>

std::stringstream sStream;
sStream << std::fixed << std::setprecision( 16 ) << (double)12; //yields 12.0000000000000000
std::string value = sStream.str();
boost::trim_right_if(value, boost::is_any_of("0")); //turn 12.000000000000000 -> 12.
boost::trim_right_if(value, boost::is_any_of(".")); //turn 12. -> 12
于 2017-01-12T09:46:48.550 に答える
0

コンパイラresultは、そのように宣言されているため、常に double です。内部的には、整数とは異なるメモリ レイアウトを持ちます。

達成したいことを適切に行うresultには、が自然数に十分近いかどうかを確認し、印刷する前に適切な整数にキャストします。

于 2012-06-15T09:45:53.777 に答える
0

結果が整数であることがわかっている場合は、整数変数を使用するか、単純に整数にキャストできます。

double result;
/*some operations on result */
printf("%d", (int)result);

[編集]次のようにしてみてください。

#include <stdio.h>
#include <math.h>
void VariablePrecisionPrinter( double num, double precision )
{
    if( fabs(num-int(num)) < precision )
    {
        printf("%d\n", (int) num);
    }
    else
    {
        printf("%g\n", num);
    }
}

void Test(  )
{
    const double Precision = 0.001;
    VariablePrecisionPrinter( 100.001, Precision );
    VariablePrecisionPrinter( 100.00001, Precision );
    VariablePrecisionPrinter( 0.00001, Precision );
    VariablePrecisionPrinter( 0.0, Precision );
    VariablePrecisionPrinter( 0.1, Precision );
}

...印刷されます:

100.001
100
0
0
0.1

[編集2]

これは少し不格好ですが、あなたが求めることを行います:

#include <string>
#include <stdio.h>
#include <math.h>

using namespace std;

void VariablePrecisionPrinter( double num )
{
    // Convert the number to a string
    const int tmpSize = 128;
    char tmp[tmpSize] = {'\0'};
    sprintf(tmp, "%lf", num);
    string truncatedNum = tmp;

    // If the conversion ends with a 0, strip the extra parts.
    size_t p2 = truncatedNum.find_last_not_of( '0' );
    if( string::npos != p2 )
    {
        truncatedNum = truncatedNum.substr( 0, p2+1 );

        // Make sure we're not left with just a decimal point at the end
        size_t decimalPos = truncatedNum.find_last_of('.');
        if( decimalPos == truncatedNum.length()-1  )
        {
            truncatedNum = truncatedNum.substr( 0, truncatedNum.length()-1 );
        }
    }

    printf( "%s\n", truncatedNum.c_str() );
}

void Test(  )
{
    const double Precision = 0.001;
    VariablePrecisionPrinter( 100.001 );
    VariablePrecisionPrinter( 100.00001 );
    VariablePrecisionPrinter( 0.00001 );
    VariablePrecisionPrinter( 0.0 );
    VariablePrecisionPrinter( 0.1 );
}
于 2012-06-15T09:40:16.680 に答える
0
string DoubleToString (double inValue)
{
   std::stringstream buildString;

   int i = 0;
   double valueWithPrecision = 0;

   do
   {
      buildString.str(std::string());
      buildString.clear();

      buildString << std::fixed << std::setprecision(i) << inValue;

      valueWithPrecision  = std::stod(buildString.str().c_str());

      i++;
   } while (valueWithPrecision  != inValue);

   return buildString.str();
}
于 2014-09-24T20:28:51.623 に答える