JNY wrote:
Hello,
I've searched for a solution, but can't find one.
When adding two numbers I'm not getting the expected result:
int testInt = 3056;
float testMant = 0.9001;
float testTotal;
testTotal = testInt+testMant;
This is producing 3056.9, not 3056.9001 as I would like. Using
doubles doesn't seem to help. Can anyone else?
Three questions
a) Why do you think floats have infinite precision?
b) Why didn't you check the FAQ before posting?
c) Why didn't you follow the newsgroup before posting. In the last week
similar questions were posted by at least three other people clueless
about this, who also violated usenet ettiquette by posting without
checking the FAQ or following the newsgroup before posting.
See if you can explain this (recompile for the limits of your system):
#include <stdio.h>
#include <float.h>
int main(void)
{
int testInt = 3056;
float testMantf = 0.9001, testTotalf;
double testMant = 0.9001, testTotal;
long double testMantl = 0.9001L, testTotall;
testTotalf = testInt + testMantf;
testTotal = testInt + testMantf;
testTotall = testInt + testMantf;
printf("float addend:\n"
" %d (int) + %.*g (float) = %.*g (float)\n"
" %d (int) + %.*g (float) = %.*g (double)\n"
" %d (int) + %.*g (float) = %.*Lg (long double)\n\n",
testInt, FLT_DIG, testMantf, FLT_DIG, testTotalf,
testInt, FLT_DIG, testMantf, DBL_DIG, testTotal,
testInt, FLT_DIG, testMantf, LDBL_DIG, testTotall);
testTotalf = testInt + testMant;
testTotal = testInt + testMant;
testTotall = testInt + testMant;
printf("double addend:\n"
" %d (int) + %.*g (double) = %.*g (float)\n"
" %d (int) + %.*g (double) = %.*g (double)\n"
" %d (int) + %.*g (double) = %.*Lg (long double)\n\n",
testInt, DBL_DIG, testMant, FLT_DIG, testTotalf,
testInt, DBL_DIG, testMant, DBL_DIG, testTotal,
testInt, DBL_DIG, testMant, LDBL_DIG, testTotall);
testTotalf = testInt + testMantl;
testTotal = testInt + testMantl;
testTotall = testInt + testMantl;
printf("long double addend:\n"
" %d (int) + %.*Lg (long double) = %.*g (float)\n"
" %d (int) + %.*Lg (long double) = %.*g (double)\n"
" %d (int) + %.*Lg (long double) = %.*Lg (long double)\n\n",
testInt, LDBL_DIG, testMantl, FLT_DIG, testTotalf,
testInt, LDBL_DIG, testMantl, DBL_DIG, testTotal,
testInt, LDBL_DIG, testMantl, LDBL_DIG, testTotall);
return 0;
}
float addend:
3056 (int) + 0.9001 (float) = 3056.9 (float)
3056 (int) + 0.9001 (float) = 3056.90014648438 (double)
3056 (int) + 0.9001 (float) = 3056.900146484375 (long double)
double addend:
3056 (int) + 0.9001 (double) = 3056.9 (float)
3056 (int) + 0.9001 (double) = 3056.9001 (double)
3056 (int) + 0.9001 (double) = 3056.90009999999984 (long double)
long double addend:i
3056 (int) + 0.9001 (long double) = 3056.9 (float)
3056 (int) + 0.9001 (long double) = 3056.9001 (double)
3056 (int) + 0.9001 (long double) = 3056.9001 (long double)