hi,
I have a problem with arduino as I was trying to do simple calculations.
int value=(240/280)*100
Serial.println(value);
The result is Zero!
hi,
I have a problem with arduino as I was trying to do simple calculations.
int value=(240/280)*100
Serial.println(value);
The result is Zero!
That's very unfortunate.
However, what is (240/280)? It is 0.857142857142857. Since we are dealing in integers, we truncate that, giving 0.
Then we multiply 0 by 100, giving 0.
So, the answer is 0!
change your data type to Float.
Int does only hold whole numbers
or go (240 x 100)/280
an int goes from -32,768 to 32,767, so you should just sneak in.
Still will only be an approx answer, but might be okay for your needs
the answer shouldn't be Zero.
(240/280)*100=85.71428571
Anything multiplied by zero is zero.
Better read up on "int" data types then. They don't have decimal places.
Well, they do, but they're all to the left of the decimal point.
Can you please explain to me how an integer has decimal points ?
and how to divide 2 16bit ints and get a decimal point
Well if you have a number that's from 0.00001 to 0.00050, you could just pretend that it's multiplied by 100,000 and say it's between 1 and 50 (or 10 and 500 or 100 and 5000)
fiddler:
Can you please explain to me how an integer has decimal points ?
I think AWOL is making a bit of a jest there. Integers are, like, 1, 2, 3, 4.
I suppose you could say that is 1.0, 2.0, 3.0, 4.0 where the numbers are "to the left of the decimal point". The implied decimal point.
As has been pointed out earlier, you can multiply first and then divide. For example, to express 3/4 as a percent:
3 * 100 / 4 = 75
That works because the expression is evaluated left-to-right.
However (with integers):
3 / 4 * 100 = 0
Because 3/4 is 0, and multiply 0 by 100 and you still get 0.
Multiplying first has its own hazards. eg. using signed 2-byte integers:
3000 * 100 / 4000 = -6
That's because 3000 * 100 is 30000 (0x493E0) which is truncated to 93E0, effectively becoming -6C20 (-27680) because the high-order bit (the sign bit) is set, divided by 4000, giving -6.
Example sketch, for anyone that doesn't believe me:
void setup ()
{
Serial.begin (115200);
int a = 3000 * 100 / 4000;
Serial.println (a);
}
void loop () {}
Output:
-6
That's because 3000 * 100 is 30000
Time for some new batteries in your calculator, I think. Make sure you get the unsigned long kind.
Blasted batteries! I knew I should have paid more for them.
Well, perhaps 3000 * 100 is 300000.
As for my calculator, my old HP 20S now, very annoyingly, just refuses to turn on more often than not. And that's with new batteries.