Page 1 of 1
How to divide int ?
Posted: 18 Sep 2010 11:51
by crocu
Hello
I'm reading a ADC value and need to do some calculations :
When i try do display on my LCD the result called "g_long"
Expected result is not correct, can you tell me what is wrong with this line please ?
Code: Select all
g_long = (((long)z_read - c) / s);
Here is code snippet i use for declarations and calculation :
Code: Select all
unsigned int z_read=0;
long g_long;
int c = 515;
int s = 163;
...
z_read = ADC_read(1); // get ADC value from 1st channel ( RA0 )
g_long = (((long)z_read - c) / s);
Many thanks for your help,
Re: How to divide int ?
Posted: 22 Sep 2010 23:45
by braus
what if you declare the whole variables as unsigned int? this 2 bytes type is enough the major times.
Re: How to divide int ?
Posted: 23 Sep 2010 07:31
by Sobrietytest
Crocu, you have only done half the calculation - after the division you then need to take care of the remainder, have a look at the modulus operator (%) in the help files.
Re: How to divide int ?
Posted: 23 Sep 2010 09:18
by crocu
The calculation result should be from -10.0 to +10.9
then, i would like to display result like this : +xx.x or -xx.x
I would like to display 1 digit after comma : if i proceed like this, it it correct ?
But i don't know how to find out if result will be + or - signed ... i need to display the sign ( + or - ) in front of the result.
Code: Select all
char result_display[6] = " 00.0";
signed int z_read=0;
signed int result;
unsigned int c = 515;
unsigned int s = 163;
...
z_read = ADC_read(1); // get ADC value from 1st channel ( RA0 )
result = (((signed int)z_read - c) / s); // calculation
// Extract each digit from "g_int" result :
result_display[2] = result% 100+ 48; // example: result = 17.2 % 100 = 1, 1 + 48 = '7' - ASCII
LCD_Chr(4,1,48+result_display[2]); // Print character on LCD
result_display[1] = result% 10 + 48; // example: result = 17.2 % 10 = 7, 7 + 48 = '7' - ASCII
LCD_Chr_CP(48+result_display[1]); // Print character on LCD
LCD_Chr_CP('.'); // Print "." character on LCD
result_display[0] = result% 1 + 48; // example: result = 17.2 % 1 = 2, 2 + 48 = '2' - ASCII
LCD_Chr_CP(48+result_display[0]); // Print character on LCD
But maybe i declared " result " as float instead of signed int and then only show 1 digit after comma.
if so i don't know how to do that.
Can someone show me the way please ?
Re: How to divide int ?
Posted: 30 Sep 2010 14:01
by crocu
Can someone help me please ?