I have the following C language code which uses pointers. I have written two similar test cases. One test case matches the output of my function with macro and other with a variable equal to that macro. I understand that floating point arithmetic can produce 'false' with ==
operation. I have read the duplicate question - 'Is floating point math broken?' But what is the solution? How can my code pass this test without changing the test. Below is the code.
#define TEST_LBS 5.5
#define CONVERSION_FACTOR 2.20462
#include <stdio.h>
void testConvertLbsKg(void);
double convertLbsKg(double *weightLbsPtr, double *weightKilosPtr);
int main() {
testConvertLbsKg();
return 0;
}
void testConvertLbsKg(void) {
double dblA, dblB, lbs = TEST_LBS;
dblA = dblB = 0.0;
printf("Test-1: \n");
dblB = convertLbsKg(&lbs, &dblA);
if (dblA == dblB && dblA == TEST_LBS / CONVERSION_FACTOR)
printf("<PASSED> with macro\n");
else
printf("<!!! FAILED with macro!!!>\n");
if (dblA == dblB && dblA == lbs / CONVERSION_FACTOR)
printf("<PASSED> with variable\n");
else
printf("<!!! FAILED with variable!!!>\n");
}
double convertLbsKg(double *weightLbsPtr, double *weightKilosPtr) {
double result;
result = *weightLbsPtr / CONVERSION_FACTOR;
if (weightKilosPtr != NULL) {
*weightKilosPtr = result;
}
return result;
}
Output:
Test-1:
<PASSED> with macro
<!!! FAILED with variable!!!>
It is an issue for me because it is an assignment and I can't modify the test case.
lbs == TEST_LBS //results to true
I installed C compiler like this: tutorial I am using Visual Code. Commands I used on VS Code terminal:
gcc -Wall test.c -o test
.\test.exe