#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?
%lfinstead of%dformat to read intodouble. Using%dindicates toscanf()that the pointer is anint *; using%lfindicates it is adouble *. Also remember to print your inputs for checking; this would have told you a lot about what's going wrong. And if your compiler wasn't warning you about the mismatch between the format string and the pointers, it is time to turn on the warnings, or get a better compiler.printf, yes - floats and doubles are treated the same. But forscanf, no - you need%fforfloatand%lffordouble.printf()andscanf()— a source of endless problems. Withprintf(), the%fformat serves for bothdoubleandfloatbecause the compiler automatically convertsfloattodoublein the call. You can now use%lffordoubleinprintf(), mainly for symmetry withscanf(). Inscanf(),%findicates afloat *argument;%lfindicates adouble *argument. You use%Lfin bothprintf()andscanf()to indicatelong double(but the types arelong doubleandlong double *, of course).%iaccepts0xABCDas a hex and007as octal and 1234 as decimal;%donly accepts decimal (and%xonly accepts hex and doesn't require the0xprefix, and%oonly accepts octal and doesn't require the 0 prefix).