8 bit pic controller coding for math division

Thread Starter

Ylee5763

Joined Sep 23, 2015
27
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.
Can anyone please provide me some advice or examples?
Thank you.
 

Papabravo

Joined Feb 24, 2006
21,226
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.
 

ErnieM

Joined Apr 24, 2011
8,377
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.
 

Thread Starter

Ylee5763

Joined Sep 23, 2015
27
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.
 

JWHassler

Joined Sep 25, 2013
306
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)
 

Papabravo

Joined Feb 24, 2006
21,226
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\)
 

Thread Starter

Ylee5763

Joined Sep 23, 2015
27
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\)
Thanks, I guess I have to apply this method, but why I have no this issue using Arduino?
 

Papabravo

Joined Feb 24, 2006
21,226
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.
 
Top