I\'m trying to compare two strings, but I fail achieving that. Why?
#include
#include
int main(){
float a = 1231.23123;
You are comparing these 2 strings here:
1231.23123
1231.231201
which are different indeed, thus strcmp
returns non-zero value.
The actual problem here is that when you do float a = 1231.23123;
, the number you want to store in a
can't be represented as a float
, the nearest number that can be represented as a float
is 1231.231201171875
in this case. Have a look at OMG Ponies!!! (Aka Humanity: Epic Fail) ;)
To solve your problem I would start with using double
instead of float
to get more precise accuracy. Then you could specify the precision (%.5lf
) while printing this number into the string to make sure that the number is rounded just like you need it:
double d = 1231.23123;
char str[32];
sprintf(str, "%.5lf", d);
// strcmp(str, "1231.23123") would return 0 here