C++实验7

本文介绍使用C++实现不同图形面积计算的方法,包括宏定义、函数定义及函数重载,并展示了如何利用静态变量生成Fibonacci数列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、宏梯形面积

#include<iostream>
using namespace std;
#define AREA(a,b,h) ((a)+(b))/2*(h)
//宏定义中将参数用括号括起来很重要,否则若h=4+5;
float area(float a,float b, float h)
{
    return (a+b)/2*h;
}
void main()
{
    float a,b,c;
    cout<<"请依次输入梯形的长、宽、高:\n";
    cin>>a>>b>>c;
    cout<<"面积是:\n";
    cout<<AREA(a,b,c)<<"(宏定义)\n";
    cout<<area(a,b,c)<<"(函数定义)"<<endl;
}

二、静态变量Fibonnaci数列

#include<iostream>
using namespace std;
void fibonaci()
{
    static int n=1;
    static int n1=1;
    static int n2=1;
    static int n3;
    if(n==1)
    {
        cout<<n1<<'\t';
        n++;//不要忘记n++,否则永远输出1;
        return;
    }
    if(n==2)
    {
        cout<<n2<<'\t';
        n++;
        return;
    }
    cout<<n1+n2<<(n%10==0?'\n':'\t');
    int temp;
    temp=n2,n2=n2+n1;n1=temp;
    n++;
}
void main()
{
    int n=20;
    cout<<"Fibonaci数列前20项为:\n";
    for(int i=0;i<n;i++)
        fibonaci();
}

三、重载函数圆、矩形、梯形面积

#include<iostream>
using namespace std;
#define _USE_MATH_DEFINES
#include<math.h>
float area(float);
float area(float,float);
//float area(float a=10,float b=10);
//这种情况下不能缺省,否则area()函数定义不明确
float area(float,float,float);
void main()
{
    cout<<area(1)<<'\n';
    cout<<area(10,20)<<'\n';
    cout<<area(10,20,10)<<endl;
}
float area(float a)
{return float(M_PI)*a*a;}
float area(float a,float b)
{return a*b;}
float area(float a,float b,float c)
{return (a+b)/2*c;}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值