Calculating negative numbers with decimals

Good evening all

I seem to have a problem with my knowledge about the operation of an Arduino.

I am trying to calculate the following value, but all that I get back from the Serial monitor is a round Zero. Any ideas on how I can go about calculating the correct values and using them in the Arduino?

float m = (1-40)/(1200-700);

By the way, I tried both a Leonardo and a Nano...

Cheers Adam

The values are integers, so the calculation is done as integer division. -39/500 = 0. Force it to be done as floating point (there are various ways):

float m = (float)(1-40)/(float)(1200-700);

Pete

All the numbers on the right-hand side are integers. It is using integer maths, which truncates all results to the next-smallest integer.

One 'trick' is to make one of those numbers a float by making it a decimal. 1.0 for example. This forces the compiler to upgrade all the numbers to floats.

The 'correct' way to do it is to use the (float) cast, to explicitly tell the compiler you want to use floats on the right-hand side.

float m = (float)(1-40)/(1200-700);

Or you can just write the numbers as floating point and skip the cast:

float m = m(1.0 - 40.0)/(1200.0-700.0);

AdamDuino: By the way, I tried both a Leonardo and a Nano...

Cheers Adam

It would do the same thing on a Cray. 8^)

Cool, thanks very much for your assistance guys. I have learned something new. It seems to do the trick.

Highly appreciated.

Cheers Adam