简体   繁体   中英

Find the area of a circle using C language

I am a beginner to coding.I have to find the area of a circle using c,I wrote the code but when I run it,it shows 'undefined reference to main'.Please explain what I'm doing wrong

What I have tried:

#include <stdio.h>

float area(float r)
{
    float area;
    
    printf("\nEnter the radius of Circle : ");
    scanf("%f", &r);
    area = 3.14 * r * r;
    printf("\nArea of Circle : %f", area);

    
    return area;

}

Instead of hard coding the magic value 3.14 use a constant. In this case math.h defines M_PI if __USE_OPEN , __USE_MISC or __USE_GNU are defined. If your math.h doesn't you can define it like this:

#ifndef M_PI
#    define M_PI 3.14159265358979323846
#endif

The entry point for a c program is the function int main() . This is your main problem.

area() takes a float r, but you populate that variable in in the function. Either leave out the argument or as shown here let caller do the I/O and pass in the argument and return the result.

Prefer trailing to leading \n as the output stream might be line buffered.

#define __USE_XOPEN
#include <math.h>
#include <stdio.h>

float area(float r) {
    return M_PI * r * r;
}

int main() {
    printf("Enter the radius of Circle : ");
    float r;
    if(scanf("%f", &r) != 1) {
         printf("scanf failed\n");
         return 1;
    }
    printf("Area of Circle : %f\n", area(r));
}

Every hosted C program has a primary function that must be named main . The main function serves as the starting point for program execution.

This program first reads the radius of the circle from the user, then calculates the area using the formula area = pi * radius^2 . Finally, it prints the result.

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

int main(void) {
  double radius;
  double area;

  // Read the radius of the circle from the user.
  printf("Enter the radius of the circle: ");
  if(scanf("%lf", &radius) != 1) // If user enter invalid stuff…
  {
    fprintf(stderr, "Error: invalid input.\n");
    return EXIT_FAILURE; // EXIT_FAILURE means error.
  }

  // Calculate the area of the circle
  area = M_PI * radius * radius;

  // Print the result
  printf("The area of the circle is: %f.\n", area);

  return EXIT_SUCCESS; // EXIT_SUCCESS means success.
}

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