C++primer习题6.1节练习

本文详细解析了C++中的函数定义与调用,通过多个实例展示了如何在控制台应用程序中使用函数进行阶乘计算、绝对值计算以及静态变量的运用。同时,介绍了如何通过头文件分离函数声明与实现,实现代码的模块化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值