# 8 bit pic controller coding for math division

Discussion in 'Embedded Systems and Microcontrollers' started by Ylee5763, Sep 23, 2015.

1. ### Ylee5763 Thread Starter New Member

Sep 23, 2015
25
1
Hi I have some difficulties to program 8 bit pic controller for math division like (1-100/132). I did find some examples in assembly codes, but there's not many examples in C.
I am using mplab X with XC8 compiler.
I use ADC value1 divded by ADC value 2, and do the equation 1 - values /value2, and I got 0 for the answer even I have used float.
Thank you.

2. ### Papabravo Expert

Feb 24, 2006
11,780
2,496
How much do you know about the algorithm(s) for performing division? If you stick to known data types the compiler and the library should take care of that for you.

3. ### ErnieM AAC Fanatic!

Apr 24, 2011
7,958
1,827
The expression (1-100/132) is a value less than one, and can only be expressed in a float; any sort of integer value conversion will make this zero.

How about posting the code where you do the conversion, and also show how you use this value.

It is extreme rare to actually require using a float when doing calculations like this. Instead values are shifted so the decimal portion is insignificant.

4. ### dannyf Well-Known Member

Sep 13, 2015
2,196
421
Unless you can show that you used the floating types correctly, the issue is likely on your end.

5. ### Ylee5763 Thread Starter New Member

Sep 23, 2015
25
1
The experiment code is very simple:
#include <htc.h>
void main (void)
{
while (1){
long a=100;
long b=132;
long c=a/b;
}
}

I have tried many different ways, and I couldn't get the result for 0.76 from debugging.

6. ### JWHassler Active Member

Sep 25, 2013
263
47
You need float, not long: 100/132 will always return zero for two integer-types. Try 132/100 and see what happens... (I hope it's 1)

7. ### Papabravo Expert

Feb 24, 2006
11,780
2,496
As I wrote earlier, you fail to understand the process of integer division. In words using as few syllables as possible: Integer division produces a quotient and a remainder, and then discards the remainder.
So
$100/132 =0, R=100
132/100=1, R=32$

8. ### Ylee5763 Thread Starter New Member

Sep 23, 2015
25
1
Thanks, I guess I have to apply this method, but why I have no this issue using Arduino?

9. ### Papabravo Expert

Feb 24, 2006
11,780
2,496
You have exactly the same problem on an Arduino, if you use integer arithmetic. All machines that use integer arithmetic behave exactly the same way. The only way to preserve a fractional value from the division of two integers is to use floating point.

10. ### dannyf Well-Known Member

Sep 13, 2015
2,196
421
If that piece of the code had produced 0.76, you should have thrown out the compiler and picked something else.