简体   繁体   中英

C program to find area

I am having problems with the following code:

#include<stdio.h>
#include<conio.h>
float area_crcl(int);
float area_rect(int,int);

void main()
 {
 int n,a,b,r;
 float area;
 clrscr();
  printf("\nEnter your choice-\n1.Area of circle\n2.Area of Square\n3.Area of Rectangle\n");
  scanf("%d",&n);
   switch(n)
     {
     case 1:printf("\nEnter the radius of circle..\n");
        scanf("%d",&r);
        area=area_crcl(r);
        printf("\nArea of circle is %d\n",area);
        break;

     case 2:printf("\nenter the edge of square\n");
        scanf("%d",&a);
        area=area_rect(a,a);
        printf("\nArea of square is %d\n",area);
        break;

     case 3:printf("\nenter the lenght n breadth of rectangle\n");
        scanf("%d%d",&a,&b);
        area=area_rect(a,b);
        printf("\nArea of rectangle is %d\n",area);
        break;

     default:printf("\nU entered wrong choice..\n");
   }
  getch();
 }

 float area_crcl(int r)
   {
    float area;
    area=3.14*r*r;
    return area;
   }

 float area_rect(int a,int b)
   {
    float area;
    area=a*b;
    return area;
   }

The output which I am getting is :

Enter your choice- 1.Area of circle 2.Area of Square 3.Area of Rectangle 1

Enter the radius of circle.. 2

Area of circle is 0

Why am I getting 0 as output?

Your print statement is:

printf("\nArea of circle is %d\n",area);

area is a float and you're using a %d format string, which is meant for int variables. That won't work - use %e , %f , %g , or %a .

For floats, use %f in printf. More generally be very careful to match % in printf's with parameters passed. No check is done and this is entirely at the programmer's charge

printf("\nArea of circle is %f\n",area);

You are using %d to print float that is your problem .

And one more thing other than your error :

Just don't get stuck with conio.h , OK ... move on in life :)

area is of type float and you are using %d specifier to print it. Functions

 area_rect()
 area_crcl()

both are returning float value which is assigned to area (which is also float)
Change

 printf("\nArea of circle is %d\n",area);

to

 printf("\nArea of circle is %f\n",area);

printf("\\nArea of circle is %d\\n",area);

Area is float so above statement will not work, use the correct one below:

printf("\\nArea of circle is %f\\n",area);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM