You are not logged in.
Here's the code:
#include <stdio.h>
const float COEFF4[2][2] = {
732974.9209,-2614372.431,
-4458973.651,15923460.62
};
int main(void) {
char stra[20];
memset(stra, 0, 20);
sprintf(stra, "%f", COEFF4[0][0]);
printf(stra);
printf("\n");
return 0;
}
[karam@kfc5s1 new]$ nano -w test.c
[karam@kfc5s1 new]$ gcc -o test test.c
[karam@kfc5s1 new]$ ./test
732974.937500
Any help is greatly appreciated...
Last edited by tony5429 (2008-09-28 04:51:26)
Offline
This is due to the internal representation of the date type, try using double instead.
First a link, then a quick explanation: http://en.wikipedia.org/wiki/IEEE_754
I might be mistaken (it's been a while, so details are blurry), but the saving of the number is done as follows:
1. Normalize the number: 732974.9209 -> 0.7329749209 (done in binary format) -> this defines the expontent
2. Cut of the first 0.1 in binary format, i.e. 0.1000110 would be 000110 -> this is the fraction part
Now the fraction is saved as expontents of 2, i.e 0.1 binary equals to 2^-1 = 0.5, 0.01 to 2^-2 = 0.25, 0.001 to 2^-3 = 0.125,...
This means it is impossible to encode some numbers like 0.2 (you can only achieve an appoxiation using exponents of 2) or 0.
In your case the precision of the fraction is simply not high enough, so a rounding to the value occurs. Using double will give you a higher precision and solve this problem.
Last edited by wuischke (2008-08-01 14:42:57)
Offline
Thanks, wuischke, although I am still having some difficulty. There is probably a simple reason for this but I can't figure it out...
#include <stdio.h>
const double COEFF4[2][2] = {
732974.9209,-2614372.431,
-4458973.651,15923460.62
};
int main(void) {
char stra[20];
memset(stra, 0, 20);
sprintf(stra, "%d", COEFF4[0][0]);
printf(stra);
printf("\n");
return 0;
}
[karam@kfc5s1 new]$ nano -w test.c
[karam@kfc5s1 new]$ gcc -o test test.c
[karam@kfc5s1 new]$ ./test
0
Offline
You should check out the documentation for printf - %d is for "decimal integer". You should keep using %f, even though you're using a double.
Offline
Haha; I knew it was something simple. Thanks to both of you; it's working now
Offline