|
|
View previous topic :: View next topic |
Author |
Message |
cuma_polat
Joined: 24 Nov 2008 Posts: 3
|
PCD: Comparing two floating point numbers |
Posted: Sun Jan 18, 2009 2:26 pm |
|
|
Hi friends,
I have a very simple problem. I want to compare two float value with "if". example program is here;
Code: | #include <30F4013.h>
#device ADC=10
#use delay(clock=10000000)
#FUSES HS
#use rs232(UART2,baud=9600,xmit=PIN_F3,rcv=PIN_F2,parity=N,bits=8)
#include <math.h>
#include <flex_lcd.c>
#use fast_io(B)
#use fast_io(C)
#use fast_io(D)
#use fast_io(F)
float n=0.1,nce=0.2,c=0;
float positive (float ee){
float nu_p;
if (n<0.0) nu_p=1;
else nu_p=2;
return ((float)nu_p);
}
void main(){
lcd_init(); // Always call this first.
while(true){
c=positive(1.0);
printf(lcd_putc,"\fc=%f ",c);
delay_ms(500);
}
} |
As you see from the code, I try to compare n with 0.0 in subprogram "positive" . It is always true because n=0.1. so nu_p must be 1.0 but LCD shows that c=2.0
On the other hand I compare n with nce in another program but it didn't give the true result although the condition was true.
Can I compare two float value with CCSC by using if-statement?
Please Help! |
|
|
ckielstra
Joined: 18 Mar 2004 Posts: 3680 Location: The Netherlands
|
|
Posted: Sun Jan 18, 2009 4:29 pm |
|
|
Quote: | It is always true because n=0.1. | This is incorrect. With n == 0.1 the comparison becomes: Code: | if (0.1 < 0.0) nu_p=1;
else nu_p=2; | The IF-statement is always FALSE and the returned value of 2 is correct. |
|
|
cuma_polat
Joined: 24 Nov 2008 Posts: 3
|
|
Posted: Sun Jun 28, 2009 6:21 am |
|
|
Yes you are right,
I wrote the wrong code, this is the right one;
Code: |
#include <30F4013.h>
#device ADC=10
#use delay(clock=10000000)
#FUSES HS
#use rs232(UART2,baud=9600,xmit=PIN_F3,rcv=PIN_F2,parity=N,bits=8)
#include <math.h>
#include <flex_lcd.c>
#use fast_io(B)
#use fast_io(C)
#use fast_io(D)
#use fast_io(F)
float n=0.1,c=0.0;
float positive (float ee){
float nu_p;
if (n<1.0) nu_p=1;
else nu_p=2;
return ((float)nu_p);
}
void main(){
lcd_init(); // Always call this first.
while(true){
c=positive(1.0);
printf(lcd_putc,"\fc=%f ",c);
delay_ms(500);
}
}
|
I compare n with 1.0, n is smaller than 1.0 but the LCD shows c=2.00.. |
|
|
FvM
Joined: 27 Aug 2008 Posts: 2337 Location: Germany
|
|
Posted: Sun Jun 28, 2009 10:55 am |
|
|
It's possibly a bug of an old PCD version. I tested the code, compiled with PCD V4.093 in MPLAB SIM (directing the output to UART instead of LCD) and it showed c=1.00. |
|
|
|
|
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
|