Reputation:
Where is the error in my code, super simple yet the comparisons are not outputting the correct values. This function below is in its own file called: FloatingPointRepresentationsFunctions.c
int FloatCompare(float number1,float number2){
// Write the function to compare and return the corresponding value
if(number1 < number2){
return -1;
}else if(number2 < number1){
return 1;
}else{
return 0;
}
}
The functions should return -1 if float 2 is greater then float 1, it should return 1 if float 1 is greater then float 2. It then should return 0 if the float values are equal.
My eclipse console output(mingW):
number1: 12.000000
number2: 11.000000
Comp: -1
11.000000 is greater than 12.000000
and here is my main c file:
#include <stdio.h>
int main()
{
float number1 = 0;
float number2 = 0;
int comparison;
number1=12;
number2=11;
printf("number1: %f \nnumber2: %f \n", number1, number2);
comparison=FloatCompare(number1,number2); // Compare two floating point numbers
printf("Comp: %d\n", comparison);
if(comparison==1){
printf("%f is greater than %f\n",number1,number2);
}else if(comparison==-1){
printf("%f is greater than %f\n",number2,number1);
}else if(comparison==0){
printf("Number are equal\n");
}else{
printf("Error\n");
}
return 0;
}
Upvotes: 2
Views: 671
Reputation: 223882
Your main file doesn't have a proper prototype for FloatCompare
. This means it assumes the default function definition of int FloatCompare()
, which results in the function being called incorrectly and undefined behavior.
You need to add a declaration to your main source file so it knows how to call the function properly.
#include <stdio.h>
int FloatCompare(float number1,float number2);
int main()
{
...
}
Upvotes: 5