arduino - Multiplication, division. What is wrong? -


simple operations. calculate time delay.

const unsigned long c1 = 30 * 1000; const unsigned long c2 = (300 * 1000)/c1; // must = 10  void setup() {   serial.begin(57600);   serial.println("\n-------");   serial.print("c1 = "); serial.println(c1);   serial.print("c2 = "); serial.println(c2);    unsigned long v1 = (300 * 1000)/c1;   // must = 10   serial.print("v1 = "); serial.println(v1);    long v2 = (300 * 1000)/30000; // must = 10   serial.print("v2 = "); serial.println(v2);    int v3 = (300 * 1000)/30000; // must = 10   serial.print("v3 = "); serial.println(v3); }  void loop() { } 

arduino uno printed in monitor console:

  • c1 = 30000 (ok)
  • c2 = 143164 (must = 10)
  • v1 = 143164 (must = 10)
  • v2 = 0 (must = 10)
  • v3 = 0 (must = 10)

what wrong?

300 * 1000 expected give 30'0000, or 0x493e0 in hexadecimal. when write (300 * 1000), arduino uses 16 bits signed integer arithmetic, result truncated 0x93e0 (or -27680 in decimal).

when divide unsigned long, result converted unsigned long , gives 0xffff'93e0 or 4'294'939'616 in decimal.

divide 30'000 , 143'164.

for v2 same: (300 * 1000) = -27680 in 16 bit signed arithmetic , -27'680 / 30'000 gives 0.


Comments

Popular posts from this blog

routing - AngularJS State management ->load multiple states in one page -

python - GRASS parser() error -

Swift game error message -