 # garbage numbers from math function

Hey all.

I just purchased an arduino and I’m having some difficulty with it.

``````double input=0;
double vout=0;
double therm=0;

void setup() {
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}

void loop() {
vout=input/255*5;
therm=5*100000;

Serial.println(therm);}
``````

If I try to combine the steps I get garbage for example if I change it to vout=analogRead(0)/255*5; it returns a 0 even though my input is around 152

also here is the strangest thing. If i try therm=510000 it gives me -15536. What on earth is it doing? I can try 5100000 and that works fine

Is it possible that I have a bad board?

Moderator edit:
`</mark> <mark>[code]</mark> <mark>`

`</mark> <mark>[/code]</mark> <mark>`

input=analogRead(0); that results in an int result, yes? do you have to 'cast' it into a double? like input = double(analogRead(0)); or something?

vout=input/255*5;

This works because you declared input to be "double" and so the calculation is done as a double.

``````vout=analogRead(0)/255*5;
``````

This fails because analogRead returns a 16-bit integer and the whole calculation is done with 16-bit integer arithmetic. if the analogRead is 152 then 152/255 is zero.

``````therm=5*10000 it gives me -15536
``````

Same problem. Both 5 and 10000 are 16-bit integers and the result won't fit in a 16-bit integer so you get a strange result.

You should read about how C/C++ handles arithmetic with different types of variables - i.e. 16-bit integers, 32-bit integers, floats etc.

Pete