码迷,mamicode.com
首页 > 其他好文 > 详细

函数的定义与调用

时间:2018-12-10 19:12:23      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:函数定义   end   oid   bsp   code   iostream   width   res   style   

函数的定义:
函数类型 函数名(形参列表){ 函数体 }
函数类型省略,默认int型,返回值与函数类型一致。无返回值的,用void型

函数的调用:被调函数(子函数)要先定义再调用,或先声明、再调用、后定义

double RectArea(double length,double width);//先声明子函数,声明语句可在主调函数之前、内部(必须在调用语句之前声明)
int main(){
    ...
    totalArea+=RectArea(length,width);//再调用
    ...
}
double RectArea(double length,double width){  }//后定义。若子函数定义在主调函数之前,则声明可省略。
#include<iostream>
using namespace std;

double RectArea(double length, double width) {//函数,长方形面积
    double result = length*width;
    return result;
    //return(length*width);//简化代码
}
double CircleArea(double r) {//函数,圆面积
    double result = 2 * 3.14*r;
    return result;
    //return(2 * 3.14*r);//简化代码
}
int main() {//主函数,被调函数定义在主调函数之前,声明省略
    double length, width;
    double r1, r2;
    double totalArea = 0;

    cout << "请输入长方形的长、宽(m)" << endl;
    cin >> length >> width;
    cout << "请输入清水池和污水池的半径(m)" << endl;
    cin >> r1 >> r2;

    totalArea += RectArea(length, width);
    totalArea += CircleArea(r1);
    totalArea += CircleArea(r2);

    cout << "工程总面积为" << totalArea <<"平方米"<< endl;
    return 0;    
}

 

函数的定义与调用

标签:函数定义   end   oid   bsp   code   iostream   width   res   style   

原文地址:https://www.cnblogs.com/xixixing/p/10098107.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!