天天看點

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;
}