# Program that requests two floating-point numbers and prints the value of their difference divided by their product

From what I understand this site help to check if my solution is proper or not..so forgive me if the header is bad.

This is my solution for the question:

#include <stdio.h>

int main()

{

double num1, num2, different, product, answer;

printf("please enter 2 floatig point numbers:\n");
printf("number one is?\n");
scanf("%lf", &num1);
printf("number two is?\n");
scanf("%lf", &num2);

if (num1 > num2)
{
different = num1 - num2;
}

if (num2 > num1)

{
different = num2 - num1;
}

if (num1 == num2)

{
different = 0;
}

product = num1*num2;

}


How bad is it?

-
Are you using C99 (the newer version of the language)? –  svick Jan 24 '13 at 11:53
@svick how do I know that? sorry im learning C for less than 2 weeks :/ –  Nir Jan 24 '13 at 12:20
That depends on your compiler. Which compiler are you using, what is its version? (Most of them should support C99, I believe.) –  svick Jan 24 '13 at 12:27
@svick I'm using xcode on macbook pro 64 bit –  Nir Jan 24 '13 at 12:28

For a newbie, your solution is ok. You can simplify it quite a bit though by using the function fabs. It's a fairly simple function: fabs(x) returns x if x >= 0, and returns -x if x < 0. So all of your if checks can be replaced by the line:

different = fabs(num1 - num2);


Note that you need to #include <math.h> for this.

Also, what happens if one of your numbers is 0? Then your product will also be 0 and your program will crash. It's always a good idea to add some basic checks. Unfortunately, with floating point numbers this can be a bit tricky, so simply doing something like:

if(product == 0.0) { ... }


may not actually work! Fixing this might be a bit tricky for someone who is just learning, but it's something to always keep in mind.

Finally, main should return an int - generally, 0 is what is returned if everything works as it should - so down the bottom should be a return 0;.

-
Testing a float against 0 (or 0.0) is going to be an exact match (its one of the few comparisons on floats that works). Also division by zero using floats is not undefined behavior (that only applies to integers). In float values division by 0 result in infinity value. –  Loki Astari Jan 25 '13 at 11:01
@LokiAstari Yeah, good point. I forgot floating point division by 0 doesn't generate a SIGFPE or equivalent, it simply yields NaN. –  Yuushi Jan 25 '13 at 14:00