C++primer习题6.1节练习

练习6.2

(a)错误,函数类型是int,但是返回值为string

(b)错误,应该为int f2(int i)

(c)错误,两个形参相同了

(d)错误,少了大括号

练习6.4

// ConsoleApplication2.cpp: 定义控制台应用程序的入口点。
//
//练习6.4_2018_7_24
#include "stdafx.h"
#include "iostream"
using namespace std;

void multiple_function(int number);
int main()
{
	int i;
	cout << "please enter a number" << endl;
	cin >> i;
	multiple_function(i);
    return 0;
}

void multiple_function(int number)
{
	int result=1;
	while (number > 1)
	{
		result = result * number;
		number = number - 1;
	}
	cout << result << endl;
	system("pause");
}

练习6.5

// ConsoleApplication2.cpp: 定义控制台应用程序的入口点。
//
//练习6.5_2018_7_24
#include "stdafx.h"
#include "iostream"
using namespace std;

void absolute_function(double number);
int main()
{
	double i;
	cout << "please enter a number" << endl;
	cin >> i;
	absolute_function(i);
    return 0;
}

void absolute_function(double number)
{
	double result;
	if (number >= 0)
		result = number;
	else
		result = -number;
	cout << result << endl;
	system("pause");
}

练习6.7

// ConsoleApplication2.cpp: 定义控制台应用程序的入口点。
//
//练习6.7_2018_7_24
#include "stdafx.h"
#include "iostream"
#include "cstddef"//用size_t来替换int
using namespace std;

size_t static_function();
int main()
{
	for(size_t count=0;count!=10;count++)
	cout << static_function() << endl;
	system("pause");
    return 0;
}

size_t static_function()
{
	size_t static i = -1;
	return ++i;
}

练习6.8

首先在头文件下新建chapter6.h,头文件中只包含对阶乘函数的声明

#ifndef CHAPTER6//习惯性加上ifndef与endif
#define CHAPTER6
void multiple_function(int number);
#endif // !CHAPTER6#pragma once

然后在源文件中新建multiple_function.cpp,其中包含了阶乘函数的具体实现

#include "stdafx.h"
#include "iostream"
using namespace std;
void multiple_function(int number)
{
	int result = 1;
	while (number > 1)
	{
		result = result * number;
		number = number - 1;
	}
	cout << result << endl;
	system("pause");
}

最后我们在主函数中来测试,发现没有了对函数的声明也是可行的。

#include "stdafx.h"
#include "iostream"
#include "chapter6.h"
using namespace std;
int main()
{
	int i;
	cout << "please enter a number" << endl;
	cin >> i;
	multiple_function(i);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_41878471/article/details/81184061