1

3 つの数値セット、測定値 (0 から 1 を含む範囲)、2 つのエラー (正と負) があります。いずれかの番号にゼロエントリ。

この要件が 1 つの場合、測定ではスキップされます (つまり、エラーの数値のみを考慮する必要があります)。例えば:

0.95637 (+0.00123, -0.02935) --> 0.96 +0.00 -0.03
1.00000 (+0.0, -0.0979) --> 1.0 +0.0 -0.1 (note had to truncate due to -ve error rounding up at first significant digit)

ここで、log10(num) を取得することでゼロ以外の最初の数字を取得するのは簡単ですが、ストリッピングと丸めをクリーンな方法で機能させようとするばかげた瞬間があります。

すべてのデータ型は double で、選択した言語は C++ です。どんなアイデアでも大歓迎!

4

5 に答える 5

2

使用する

cout.setf(ios::fixed, ios::floatfield);
cout.precision(2);

数値を出力する前に、探していることを行う必要があります。

編集:例として

double a = 0.95637;
double b = 0.00123;
double c = -0.02935;

cout.setf(ios::fixed, ios::floatfield);
cout.precision(2);
cout << a << endl;
cout << b << endl;
cout << c << endl;

出力します:

0.96
0.00
-0.03

さらに編集:有効数字に合わせて精度を調整する必要があることは明らかです。

于 2009-06-05T22:43:40.313 に答える
2

私のC ++はさびていますが、次のようにはなりません:

std::string FormatNum(double measurement, double poserror, double negerror)
{
  int precision = 1;  // Precision to use if all numbers are zero

  if (poserror > 0)
    precision = ceil(-1 * log10(poserror));
  if (negerror < 0)
    precision = min(precision, ceil(-1 * log10(abs(negerror))));

  // If you meant the first non-zero in any of the 3 numbers, uncomment this:
  //if( measurement < 1 )
  //  precision = min(precision, ceil(-1 * log10(measurement)));

  stringstream ss;
  ss.setf(ios::fixed, ios::floatfield);
  ss.precision( precision );
  ss << measurement << " +" << poserror << " " << negerror ;
  return ss.str();
}
于 2009-06-05T22:58:15.010 に答える
1

たぶん次のようなもの:

std::string FormatNum(double num)
{
  int numToDisplay ((int)((num + 0.005) * 100.0));
  stringstream ss;
  int digitsToDisplay(abs(numToDisplay) % 100);
  ss << ((num > 0) ? '+' : '-') << (abs(numToDisplay) / 100) << '.' << (digitsToDisplay / 10) << (digitsToDisplay % 10);
  return ss.str();
}

    stringstream ss;
    ss << FormatNum(0.95637) << ' ' << FormatNum(+0.00123) << ' ' << FormatNum(-0.02935);
于 2009-06-05T22:18:04.140 に答える
0

log10 が最初のゼロ以外の数字を取得するのにどのように役立つかはよくわかりませんが、そうであると仮定すると (したがって、丸め先の小数点以下の桁数がわかります)、次の関数は正しく丸められます。

double round(double num, int decimalPlaces)
{
    //given your example of .95637 being rounded to two decimal places
    double decimalMultiplier = pow(10, decimalPlaces); // = 100
    double roundedShiftedNum = num * decimalMultiplier + 0.5; // = 96.137
    double insignificantDigits = (roundedShiftedNum - (int)roundedShiftedNum; // = 0.137
    return (roundedShiftedNum - insignificantDigits) / decimalMultiplier; // = (96.137 - 0.137)/100 = 0.96
}

これは最もエレガントな解決策ではないかもしれませんが、うまくいくと思います(試したことはありません)

于 2009-06-05T22:43:33.073 に答える
0

以下は、 Shane Powellによって提供されたバージョンのバリエーションです。

std::string FormatNum(double num, int decimals)
{
    stringstream ss;
    if (num >= 0.0)
        ss << '+';
    ss << setiosflags(ios::fixed) << setprecision(decimals) << num;
    return ss.str();
}
于 2009-06-05T22:54:04.677 に答える