简体   繁体   中英

Programming C calling function area of circle and rectangle

#include <stdio.h>
#define PI 3.14159
int Circle (int);
int Rectangle (int, int);
int main()
{
    int a;
    int b;
    int c;
    int d;
    int area;
    int AreaOfCircle;
    int AreaOfRectangle;
    int area1;


    printf("Program to calculate area\n");
    printf("1 - Circle\n");
    printf("2 - Rectangle\n");
    printf("\n");
    printf("What option = \n");
    scanf("%d", &a);

    if(a=1)
    {
        area=Circle(b);
        printf("Area= %d\n", area);
    }
    else if(a=2)
    {
        area1=Rectangle(c,d);
        printf("Area= %d\n", area1);
    }
    return 0;
}
  int Circle (int b)
  {
    int area;
    printf("radius= \n");
    scanf("%d", &b);
    area=PI*b*b;

    return area;
  }
  int Rectangle(int c, int d)
  {
    int area1;
    printf("length= \n");
    scanf("%d",&c);
    printf("width= \n");
    scanf("%d",&d);
    area1=c*d;

    return area1;
  }

//I want to ask if my coding is ok .. but as I run it the output only ask for radius which is the calling function for circle .. but if i want to call rectangle the output also shows calculation for circle .. can someone help me to spot the mistake .. by the way this is my first coding about calling function and I just started learning coding c last month .. TT

With C you use == to evaluate (eg if (x == 1)). "=" is assignment, so you'll always hit the first block.

Also, you're accepting parameters which you're then modifying, which is not good practice. Consider declaring your variables at usage time also, the "everything at the top of the block" paradigm is very dated.

This question is not about functional programming, this is an example of imperative programming.

Also, your input being poured directly into an integer is not bounds checked, consider a switch/case so you can add a default of "invalid input" and extend to different shapes in the future.

是的,兄弟只是使if(a == 1)否则为if(a == 1)。

You've used the assignment = operator instead of the comparison == operator.

A statement like

if(a=1)

will assign a value of 1 to a and check then check for the non-zero value of a [which always evaluates to TRUE].

Instead, what you want is

if (a == 1)

which evaluates to TRUE if a contains 1 . Same for other comparison(s) also.

Note: In your int Circle (int b) case you're storing the result to an int , which will truncate the result of a double / float multiplication. To get the exact value, make the area as float or double and use %f / %lf format specifier.

Next, as per the logical part, you don't need to pass b , c , d as parameters to the called functions. Simply a local variable in the functions would do the job.

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