簡體   English   中英

使用 C 語言計算圓的面積

[英]Find the area of a circle using C language

我是編碼的初學者。我必須使用 c 找到圓的面積,我編寫了代碼但是當我運行它時,它顯示“對 main 的未定義引用”。請解釋我做錯了什么

我試過的:

#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;

}

而不是硬編碼魔術值 3.14 使用常量。 在這種情況下,如果定義了__USE_OPEN__USE_MISC__USE_GNU ,則 math.h 定義M_PI 如果你的 math.h 沒有,你可以這樣定義它:

#ifndef M_PI
#    define M_PI 3.14159265358979323846
#endif

c 程序的入口點是 function int main() 這是你的主要問題。

area()采用浮點數 r,但您將該變量填充到 function 中。要么省略參數,要么如此處所示讓調用者執行 I/O 並傳入參數並返回結果。

更喜歡尾隨前導\n ,因為 output stream 可能是行緩沖的。

#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));
}

每個托管的C程序都有一個主程序 function 必須命名為main main function 作為程序執行的起點。

該程序首先從用戶那里讀取圓的半徑,然后使用公式area = pi * radius^2計算面積。 最后,它打印結果。

#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.
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM