[C]圆的面积,直角三角形的斜边长,macro

 

 

#include <stdio.h>
#define PI 3.1415926 //结尾不需要分号
#define area(r) (PI*(r)*(r)) //整体带括号,内部变量带括号 注意:macro中的变量是没有类型的
int main()
{
    double radius;
    printf("input a radius: ");
    scanf("%lf", &radius);
    if (radius < 0) {
        //printf("radius can't be negative.\n");
        puts("radius can't be negative.");
    }
    else {
        printf("The area of a circle with a %f radius is %f\n", radius, area(radius));
    }
}

 

三角形的斜边

#include <stdio.h>
#include <math.h> //需要先调用 math.h 头文件,sqrt, pow 都需要,编译时不要忘记加 结尾加上 -lm
#define hypotenuse(a, b) (  sqrt( (pow(a,2)) + (pow(b,2)) )  ) //括号用空格分开,便于阅读
int main()
{
    int a, b;
    printf("input two numbers: ");
    scanf("%d%d", &a, &b);
    //double c = sqrt(a * a + b * b);
    printf("%f\n", hypotenuse(a,b));

#undef hypotenuse //结尾同样不需要分号

    // printf("%f\n", hypotenuse(3,4)); //这时这里的hypotenuse就是没有定义的了
    return 0;
}

 

 

其实math.h中就有hypot函数来直接计算斜边

#include <stdio.h>
#include <math.h>
int main()
{
    int a, b;
    printf("input two numbers: ");
    scanf("%d%d", &a, &b);
    printf("%f\n", hypot(a,b)); //直接调用double hypot(double a, double b)函数
    return 0;
}

 

posted @ 2020-06-10 22:45  profesor  阅读(192)  评论(0编辑  收藏  举报