1

I am writing a program to calculate a rectangle's area.

Eg.

Enter top left point: 1 1 (User input)
Enter bottom right point: 2 -1 (User input)
Top Left x = 1.000000 y: 1.000000
Bottom Right x = 2.000000 y: -1.000000
Area = 2.000000 (Program output)

But mine is:

Enter top left point: 1 1 (User input)
Enter bottom right point: 2 -1 (User input)
w: 1.000000
h: 2.000000
w*h: 2.000000
Rectangle Area: 1.000000 // This is the problem, it should be printed out as 2.000000 instead.

.

typedef struct { 
    double x; 
    double y; 
} Point; 


typedef struct { 
    Point topLeft; /* top left point of rectangle */
    Point botRight; /* bottom right point of rectangle */
} Rectangle; 


Point p;
Rectangle r;


printf("Enter top left point : ");
scanf("%lf",&r.topLeft.x);
scanf("%lf",&r.topLeft.y);
fflush(stdin); 
printf("Enter bottom right point : ");
scanf("%lf",&r.botRight.x);
scanf("%lf",&r.botRight.y);
computeArea(&r);
printf("Rectangle Area : %lf",r);



double computeArea(Rectangle *r)
{ 
    double h=0,w=0,z=0;
    w=fabs(r->topLeft.x - r->botRight.x);
    printf("w : %lf\n",w);
    h=fabs(r->botRight.y - r->topLeft.y);
    printf("h : %lf\n",h);
    z=w*h;
    printf("w*h : %lf\n",z);
    return (z);
}
herohuyongtao
  • 49,413
  • 29
  • 133
  • 174
  • 2
    Your program is just doing what you told it to do. Check the value you are printing in main(). – mfro Mar 16 '14 at 09:50

3 Answers3

2

you cannot print a Rectangle

Rectangle r;
// ...
printf("Rectangle Area : %lf",r); // <== you cannot print a Rectangle with printf

Turn on your compiler warnings

pmg
  • 106,608
  • 13
  • 126
  • 198
0

Change:

computeArea(&r);
printf("Rectangle Area : %lf",r);

to:

printf("Rectangle Area : %lf", computeArea(&r));

As others have already noted, yiu need to add a prototype for computeArea before main (or move the whole function above main), and you should enable compiler warnings, then understand and fix all resulting warnings.

Also note that you should not use fflush(stdin) - never call fflush on an input stream - it results in undefined behaviour on most systems.

Paul R
  • 208,748
  • 37
  • 389
  • 560
0

Since nobody has actually explained the issue itself, problem is line computeArea(&r);

That function gives result as return value, which you then ignore completely. You can store it in a variable like this:

double area = computeArea(&r);

Then you can print the double value like this:

printf("Rectangle Area : %f", area);

You could also just call the function in the argument list without adding a variable, like shown in another answer. Point is, you need to catch the return value.

Note: use just %f with both double and float (which is automatically coerced to double when using printf or other variable argument function). See here for more about that.

Community
  • 1
  • 1
hyde
  • 60,639
  • 21
  • 115
  • 176