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;

    answer = different/product;

    printf("%lf", answer);


How bad is it?

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

1 Answer 1


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;.

  • 1
    \$\begingroup\$ 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. \$\endgroup\$ Jan 25, 2013 at 11:01
  • \$\begingroup\$ @LokiAstari Yeah, good point. I forgot floating point division by 0 doesn't generate a SIGFPE or equivalent, it simply yields NaN. \$\endgroup\$
    – Yuushi
    Jan 25, 2013 at 14:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.