Go Down

### Topic: division (Read 1 time)previous topic - next topic

#### Rian

##### Mar 09, 2012, 03:45 am
when i run this code i get zero why ??
Code: [Select]
` analogHigh  = Serial.read( );      analogLow = Serial.read();      x = (analogLow + (analogHigh * 256));      X = ((x/1024)*1.2);      Serial.print("x=");      Serial.print( X, DEC);      Serial.print(" , ");`

but when i delete X = ((x/1024)*1.2);

i get the value right but i want it to do the above equation ? any suggestion  ?

#### el_supremo

#1
##### Mar 09, 2012, 03:59 am
If you have declared x and X (bad choice of names by the way) to be integers then (x/1024) will be zero whenever x is less than 1024.

Pete

Don't send me technical questions via Private Message.

#### Rian

#2
##### Mar 09, 2012, 04:21 am

i actually have it less then 1024

the answer should be = 0.5859
so i should declare my X to double or float ??
am confused with double and float which one should i use ??

thanks

#### John_S

#3
##### Mar 09, 2012, 04:40 am
Use float. In Arduino, double does the same thing though.

Just wanted to add, in most cases, it is best to multiply before dividing when working with integers.
if x = 20, (x/100)*25 = 0 ...but (x*25)/100 = 5

#### Rian

#4
##### Mar 09, 2012, 04:43 am
thats good point thanks

#### el_supremo

#5
##### Mar 09, 2012, 04:44 am
One way ot fix it is to change 1024 to 1024.0 which will then force the division as floating point instead of integer.
And declare X to be float or double. Float gives about 6 digits of precision and double gives about 12 (IIRC).
You will also have to change Serial.print( X, DEC); to Serial.print( X, 4); so that X is printed as a floating point number with 4 digits after the decimal point (or however many you want).

Pete
Don't send me technical questions via Private Message.

#### Rian

#6
##### Mar 09, 2012, 04:57 am
thanks for that . well can i do like if i have x= 0.26 how can i make it = 0.3 which to a proximation value ??

#### robtillaart

#7
##### Mar 09, 2012, 07:59 am

x = x + roundingNr;
x = int(x*Factor)/Factor;

homework: find the two variables roundingNr and Factor ...
Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)

#### John_S

#8
##### Mar 10, 2012, 04:34 am
Quote
Float gives about 6 digits of precision and double gives about 12 (IIRC).

Although that may be the case in other programming languages, in Arduino float and double are essentially the same

http://arduino.cc/en/Reference/Double

#### el_supremo

#9
##### Mar 10, 2012, 05:03 am
Oooops. Thanks John.

Pete
Don't send me technical questions via Private Message.

Go Up