2.3 使用函数

Posted: March 25, 2011 in C++

/*如果函数要返回一个值就不能使用void,
函数由函数头和函数体组成,而函数头又由返回类型, 函数名和参数组成.
函数参数能够将值传给函数.*/

#include <iostream>

using namespace std;

int Add(int a, int b) //因为要返回一个值,所以这里要写入参数名a,b.
{
                  cout<<“Get the a: “<<a<<endl<<“Get the b: “<<b<<endl;
                  return (a+b);//这里用到了参数名.
}

void main()
{
                  int a,b,c;

                  cout<<“Enter the 1st number: “;
                  cin>>a;
                  cout<<“Enter the 2nd number: “;
                  cin>>b;

                  c=Add(a,b); //c等于把a和b放入Add函数里的结果,且运行函数Add,返回值已存入c.
                 cout<<“The result is “<<c<<endl;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s