10-17-2013 03:09 AM
Ich habe folgendes Problem:
float amplitude;
--------------------------------------------------
amplitude=4000/60*8;
Ergebnis: großer Fehler
amplitude=528
--------------------------------------------------
amplitude=8*4000/60;
Ergebnis: kleiner Fehler
amplitude=533
--------------------------------------------------
amplitude=4000.0/60*8;
Ergebnis: Ok
amplitude=533.333
-------------------------------------------------
Wieso rundet der Compiler so?
Kann der Compiler umgestellt werden?
Machen daß alle Compiler so, oder nur National?
Danke für Deine Antwort!
10-17-2013 03:26 AM - edited 10-17-2013 03:29 AM
Sorry for answering in English
How values are treated by C is greatly influenced on how they are written and the implicit data type associated.
4000/60*8: in this case all values are treated as integers, and the result of the operation is correct in this respect. The large error strictly depend on the (integer) division performed as the first
8*4000/60: similar discussion. The error is smaller since the division is executed last on greater values.
4000.0/60*8: in this case, 4000.0 is considered a double value, and the compiler automatically promotes all other values to the double one, producing correct results. The same would apply if you have a double variable in the calculation: no matter if other variables are integers: they are promoted to double while performing the calculation.
In this page automatic type promotion rules are listed.