次の方法で文字列を科学的記数法でフォーマットすることは可能ですか?
指数で固定位置を設定:1
仮数で小数点以下の桁数を設定:0
double number = 123456.789
したがって、数値をフォーマットする必要があります
1e+5
仮数に小数点以下0桁を設定できません:
cout.precision(0);
cout << scientific << number;
結果:
1.234568e+005
次の方法で文字列を科学的記数法でフォーマットすることは可能ですか?
指数で固定位置を設定:1
仮数で小数点以下の桁数を設定:0
double number = 123456.789
したがって、数値をフォーマットする必要があります
1e+5
仮数に小数点以下0桁を設定できません:
cout.precision(0);
cout << scientific << number;
結果:
1.234568e+005
指数フィールドで1桁を取得する方法がわかりませんが、以下は他のすべての要件に一致します。
#include <iostream>
#include <iomanip>
int main()
{
const double number = 123456.789;
std::cout << std::setprecision(0) << std::scientific << number << std::endl;
}
出力:
1e + 05
編集:
標準(N3291)をすばやく検索しましたが、科学的記数法を使用したときに指数フィールドの桁数について説明しているものは見つかりませんでした。これは実装で定義されている可能性があります。
あなたが使用している C++ コンパイラの指数が 3 桁であるかどうかはわかりません。C および C++ 標準では最低 2 桁が必要であり、g++ はそれを行っています。標準の C または C++ I/O 関数を使用して 1 桁だけを取得する方法はないため、独自のソリューションを作成する必要があります。浮動小数点から文字列への変換は非常に難しい問題[PDF] であるため、変換を行わずに結果を後処理することを強くお勧めします。
これを行う1つの方法は次のとおりです。
// C version; you can rewrite this to use std::string in C++ if you want
void my_print_scientific(char *dest, size_t size, double value)
{
// First print out using scientific notation with 0 mantissa digits
snprintf(dest, size, "%.0e", value);
// Find the exponent and skip the "e" and the sign
char *exponent = strchr(dest, 'e') + 2;
// If we have an exponent starting with 0, drop it
if(exponent != NULL && exponent[0] == '0')
{
exponent[0] = exponent[1];
exponent[1] = '\0';
}
}
文字列を取得したら、実際には何でもフォーマットできます。より多くの C++ コードは次のようになります。
const double number = 123456.789;
const int expSize = 1;
std::ostringstream oss;
std::string output;
oss << std::scientific << number;
unsigned int ePos = oss.str().find("e");
unsigned int dPos = oss.str().find(".");
if(ePos == 0){
//no exponent
}
else if(dPos == 0){
//not decimal
}
else{
output = oss.str().substr(0, dPos) + oss.str().substr(ePos, 2);
if(oss.str().size()-expSize > ePos+1)
output += oss.str().substr(oss.str().size()-expSize, oss.str().size());
else{
//expSize too big (or bug -> e used but no exponent?)
}
std::cout << output;
}
出力:
1e+5
expSize で指数サイズを設定できます。これは、任意の大きな指数に対して機能します。
それが役に立てば幸い!