C++自学之路:2.4--函数

来源:互联网 发布:任天堂vr知乎 编辑:程序博客网 时间:2024/06/08 04:03
 #include <iostream> #include <cmath>  int main(int argc, const char * argv[]) {      using namespace std;     double area;     cout << "Enter the floor area, in square feet, of your home: ";     cin >> area;     double side;     side = sqrt(area);     cout << "That's the equivalent of a square " << side     << " feet to the side." << endl;     cout << "How fascinating!" << endl;          return 0; }
 1.有返回值的函数将生成一个值,这个值可以赋值给变量或者在其他表达式中使用。
 2.sqrt函数,area是发送给函数的消息(参数),函数执行完毕后,返回一个值并赋值给side。
 3.C++程序应该为程序中使用的每个函数提供原型。
 4.函数的原型相当于变量的声明。
 5.double sqrt(double);,sqrt的函数声明。第一个double代表函数将返回一个double类型的值。括号中的double代表函数需要一个double类型的参数。原型结尾的分号代表这是一个原型,而不是函数头。如果省略分号,编译器会认为这是一个函数头并要求补充函数体。
 6.函数原型只描述函数接口。函数定义负责函数的具体实现。

 7.首次使用函数前,通常把原型放到main()函数前定义,上例通过cmath文件来提供函数的原型。


 void simon(int); int main(int argc, const char * argv[]) {      using namespace std;     simon(3);     cout << "Pick an integer: ";     int count;     cin >> count;     simon(count);     cout << "Done!" << endl;          return 0; }      void simon(int n) {     using namespace std;     cout << "Simon says touch your toes " << n << " times." << endl; }
 1.函数格式,simon()和main()函数定义格式相同,函数头+函数体。
 2.不允许函数的定义在另一个函数中,每个函数都是平等的。
 3.void simon(int n),void表示该函数没有返回值。