2

コードサンプルがあります:

float f = 3.55f;
printf("%.1f\n", f);

結果は、望ましい 3.6 ではなく 3.5 です。

float delta = 1e-7;
float f = 3.55f;
printf("%.1f\n", f+delta);

現在、結果は 3.6 ですが、f が 0.0499999f の場合。

printf("%.1f\n", f+delta);

結果は 0.0 ではなく 0.1 であることが判明しました。

3.55 を 3.6 に、0.0499999 を 0.0 に変換する関数が必要です。誰か手掛かりを教えてください。

4

6 に答える 6

0

Q: ... 3.55 を 3.6 に、0.0499999 を 0.0 に変換する関数は ...?
A: @Knnnug の回答を使用しますが、小数点以下 1 桁までです。

f = round(f * 10) / 10.0;

3.5数値が元々3.55fではないのでお渡しします。f確かに、テキスト「3.55」を使用して初期化しましたがC、コンピューターはその数値を正確に表すことができませんでした。 お使いのシステムには (float) 3.55 はありません。代わりに、最も近い選択肢であるため、fabout の値があります。3.549999952...

3.5 ではなく 3.6 に丸めて表示したい場合は、少し調整する必要あります。値が >= 3.55 である場合( 0.0499999も正確に表現できない場合)、同じナッジがそれを< 0.5 に保つナッジ。ff3.549999952...f0.04999990016...f

増加fして変化を確認できる最小値は ですnextafterf(f, g)g移動したい値です。

3.549999952...   --> 3.550000190...
0.04999990016... --> 0.04999990389...

printf("%.1f\n", nextafterf(f, 2*f));
// prints 3.6 when f is 3.549999952...
// prints 0.0 when f is 0.04999990389...

@Oli Charlesworth の回答の参照を確認することをお勧めします。

于 2013-06-09T23:36:04.390 に答える
-1

ここで、このコードは機能します。あなたがそれを理解できるように、私はコードにコメントしました。

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

int main(int argc, char const *argv[])
{
    float delta = 1e-7;
    float f = 3.55f;

    // Here we minus f (3.55) from the integer of f (3) so 3.55 - 3 = 0.55
    // Then we check whether the value is bigger than 0.5
    if( (f-(int)f) >= 0.5 ) { 
            // If it is, then plus 0.01 to the answer. Thus making it 3.65
        f = f + 0.01;
    } else {
            // If its not, minus 0.01 from the answer.
            // Assuming f is 3.44 this will make f 3.43
        f = f - 0.01;
    }

    // Since you its to the first decimal place, the code above will output 
    // your desired result which is 3.6.
    printf("%.1f\n", f+delta);
    return 0;
}
于 2013-06-08T15:09:00.850 に答える