Callum Hunt
Callum Hunt

Reputation: 9

Passing variables to functions in C

#include <stdio.h>
//function prototype
double triangle(double b ,double h);
//main function
int main(void)
{
    //declare variables
    double height,base, ans;
    //take input
    printf("Please give the height of the triangle:");
    scanf("%d",&height);
    printf("Please give the base of the triangle:");
    scanf("%d",&base);
    //pass variables to triangle function and equal returned value to ans
    ans = triangle(base,height);
    //prdouble returned doubleeger
    system("CLS");
    system("COLOR C");
    printf("\n\n\t\t\tThe area of the triangle is: %d\n\n\n", ans );
    return 0;
}
//area function
double triangle(double b, double h)
{
    printf("Hello");
    //declare varible 
    double a;
    //process data
    a = (b*h)/2;
    //return ans to main
    return (a);

}

Above is the code for a program to compute the area of a triangle, but while it works when I use integers, when I try to use doubles it fails to run the "triangle" function. Could I get some advice on why this is?

Upvotes: 0

Views: 131

Answers (5)

Noah
Noah

Reputation: 1731

%d is actually used for integer despite looking like it might represent double (I like to think of %d as digit) .

%f is used for floating point numbers.

%lf is used for double type. double is a type of float with double the number of bits. double usually has 64 bits and float is usually 32 bits. The l is a length modifier for the larger type. (I like to remember it as 'long float'.)

Upvotes: 1

user5533608
user5533608

Reputation:

as others have said, you need to change the type that you neeed to take from the user.

scanf("%lf %lf", &height, &base);

this should do the trick. good luck M8.

P.S "%lf" and "%f", both give you the same result. six digits of precision after the decimal point.

Upvotes: 0

undur_gongor
undur_gongor

Reputation: 15954

%d as format string of scanf is used for int values. For float values you need %f (or %lf for doubles).

A mismatch between format string and pointer type is "undefined behavior" and can lead to all kind of errors (or even just work in some cases).

Upvotes: 2

Callback Kid
Callback Kid

Reputation: 718

Without knowing what "fails" means in your question I would try and change your scanf statements to use the double format specifier %lf rather than %d.

scanf("%lf", &height);

Upvotes: 0

nnn
nnn

Reputation: 4220

Use %lf to read double numbers:

scanf("%lf",&height);
scanf("%lf",&base);

Use %f to print double or float variables:

printf("\n\n\t\t\tThe area of the triangle is: %f\n\n\n", ans );

Upvotes: 2

Related Questions