|
|
View previous topic :: View next topic |
Author |
Message |
tristan
Joined: 17 Jun 2005 Posts: 1
|
Typecast , Rounding issues with printf... |
Posted: Fri Jun 17, 2005 11:48 am |
|
|
I want to be able to adjust a timer value ranging from 0.0 Seconds to 25.5 seconds with a 0-255 byte variable (tim_val) using printf to show the value on the LCD with one decimal point.
Here is my fprint display line :
printf(lcd_putc,"\fT%C: \n%S %2.1f Sec",timer_num,LCDMSG[12+language],(float)tim_val/10); // display Timer adjust screen
The problem is that this works fine most of the time ... but:
0.7 , 0.9 , 1.4 , 1.8 , 1.9 , 2.3 , 2.8 , 3.3 , 3.6 seconds and so on won't show up...
I used %2.2f Sec instead to figure out what was going on, i saw that:
After 0.60 comes 0.69 ,
After 0.80 comes 0.89 ,
After 1.30 comes 1.39 and so on...
Is there a simple way to fix this and get (0.0 TO 25.5) in 0.1 second increments displaying properly on the LCD?
Thanks... |
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Fri Jun 17, 2005 12:51 pm |
|
|
I made a test program using PCM vs. 3.225 and it works OK.
Look at how I do the math in the printf() statement. I make
certain that the compiler knows that "10" is a float, by writing
it as "10.0". I also make the compiler round off the result
properly by adding half of your desired precision (on the right
side of the decimal point) to the result.
Code: | #include <16F877.H>
#fuses XT, NOWDT, NOPROTECT, BROWNOUT, PUT, NOLVP
#use delay(clock = 4000000)
#use rs232(baud=9600, xmit=PIN_C6, rcv=PIN_C7, ERRORS)
//===================
void main()
{
int8 tim_val;
for(tim_val = 0; tim_val < 255; tim_val++)
{
printf("%u %2.1f \r",tim_val, (tim_val/10.0) + .05);
}
while(1);
} |
Here is the output:
Code: |
0 .0
1 .1
2 .2
3 .3
4 .4
5 .5
6 .6
7 .7
8 .8
9 .9
10 1.0
11 1.1
12 1.2
13 1.3
14 1.4
15 1.5
16 1.6
etc. |
|
|
|
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
Powered by phpBB © 2001, 2005 phpBB Group
|