Search code examples
chypotenuse

C Program to find hypotenuse, hypotenuse found too big


This is my first program in C. When I run this the hypotenuse it finds is huge. I enter side A and B as 2 and the output is 130899047838401965660347085857614698509581032940206478883553280.000000. What did I do wrong?

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int die(const char *msg);
double hypotenuse(double side0, double side1);

int main()
{
    double a, b, c;
    printf("Enter side A: ");
    if (scanf_s("%1f", &a) != 1)
        die("input failure");
    printf("Enter side B: ");
    if (scanf_s("%1f", &b) != 1)
        die("input failure");
    c = hypotenuse(a, b);
    printf("The hypotenuse is %f\n ", c);
}

int die(const char *msg)
{
    printf("Fatal Error: %s\n", msg);
    exit(1);
}

double hypotenuse(double side0, double side1)
{
    return sqrt((side0 * side0) + (side1 * side1));
}

Solution

  • There is a typo in your scanf() conversion specifier: %1f should be %lf with an ell instead of a one.

    These 2 characters look deceptively similar. For this reason, it is also recommended to avoid naming variables l or ll, l1 etc.

    The specifier %1f attempts to convert at most 1 byte from the stream as a floating point number and store the result into a float whose address is passed. You pass the address of a double, so the behavior is undefined. You can prevent this kind of silly mistake by increasing the warning level:

    • gcc -Wall -Wextra -Werror
    • clang -Weverything -Werror
    • cl /W3 or cl /W4 or cl /Wall