C++Primer第五版 第六章函数习题(1-10)

1.实参与形参的区别?
实参:实参是形参的初始值,调用函数时传递的值。

形参:函数定义的时的参数,没有进行赋值。

int   faction1(int a)                 //函数形参
{
	return a;
}

int _tmain(int argc, _TCHAR* argv[])
{
	faction1(50);                    //函数实参

	return 0;
}

2.指出下列的错误。

(a)返回值类型不匹配

(b)函数在没有任何返回值时添加void

(c)函数的两个形参名字重复

(d)c++的语法函数定义时必须使用花括号

3.编写自己的fact函数

//比较大小
int fact(int a,int b)
{
	if (a>=b)
	{
		return a;
	}
	else
	{
		return b;
	}

}

4.编写一个与用户交互的函数,用户输入一个数字 计算阶层 并输出。

#include "stdafx.h"

//求阶层的函数
void jiaohu()
{

	int a;
	printf("求输入一个数字\n");
	scanf_s("%d",&a,sizeof(a));        //接受字符

	for (int i = a-1; i >1; i--)
	{
		a = a*i;
	}
	printf("阶层是%d", a);
}

int _tmain(int argc, _TCHAR* argv[])
{
	
	jiaohu();                         //主函数中调用
	return 0;
}

5.编写一个函数输出其实参的绝对值

#include "stdafx.h"

//输出绝对值

void absolute(int a)
{

	if (a<0)
	{
		printf("绝对值是%d",-a);
	}
	else
	{
		printf("绝对值是%d", a);
	}

}

int _tmain(int argc, _TCHAR* argv[])
{
	//调用绝对值函数
	absolute(-5);
	return 0;
}

6.说明形参 局部变量 以及局部静态变量的区别 编写一个函数 同时用到这三种形式

形参:被实参初始化 随着函数的调用结束被销毁   本质也是局部变量

局部变量:作用域是代码块 或则函数内

局部静态变量:只被初始化一次 作用域贯穿整个程序

#include "stdafx.h"
#include<iostream>
#include <string>
#include <vector>
using namespace std;



int fact()							//如果有形参
{
	static int ctr = 0;					//局部静态变量 函数结束依然存在 只初始化一次
	ctr++;
	return ctr;
}


int _tmain(int argc, _TCHAR* argv[])
{

	for (int i=1; i <=10;i++)				//i就是局部变量 随着for循环的结束销毁
	{
		cout << fact() << endl;            
	}

	cout << fact() << endl;					//静态局部变量没有被销毁 贯穿整个程序 结果是11
	return 0;
}

7.编写一个函数 第一次被调用返回0,以后每次调用返回值加1

#include "stdafx.h"
#include <iostream>
using namespace std;

//用到静态局部变量的知识
int fact()
{
	static int i=0;
	return i++;
}


int _tmain(int argc, _TCHAR* argv[])
{
	cout << fact() << endl;					//第一次返回0
	cout << fact() << endl;					//	以后调用都加1
	return 0;
}

8.编写Chapter6.h的头文件 

#include <iostream>
#include <string>
#include <vector>
using namespace std;

//头文件包含函数的声明
int fact(int My_number);
int fun();

9.理解编译器是如何支持分离式编译的。

分离式编译,C++允许我们将程序分割到几个文件中去,每个文件独立编译

这里可以将函数的定义放到.cc文件中,main()函数放到另一个.cc文件中。

10.编写函数使用指针形参编写交换两个整数的值

#include "stdafx.h"
#include <iostream>
using namespace std;

void fact(int *a,int *b)                         //指针形参可以改变实参的值
{
	int c = *a;
	*a = *b;
	*b = c;

}


int _tmain(int argc, _TCHAR* argv[])
{
	int i = 5;
	int j = 9;
	fact(&i, &j);
	printf("i是%d,j是%d", i, j);                  //输出结果正好相反
	
	return 0;
}
原创文章 4 获赞 2 访问量 421

猜你喜欢

转载自blog.csdn.net/Jabez_Lee/article/details/81366995