C++Primer第五版 6.1.2节练习

练习6.8:编写一个名为Chapter6.h的头文件,令其包含6.1节练习(第184页)中的函数声明。
答:见云盘程序

Chapter6.h

/*
*练习6.8 
*日期:2015/6/9
*问题描述:练习6.8:编写一个名为Chapter6.h的头文件,令其包含6.1节练习(第184页)中的函数声明。
*功能; fact(),fact1()求阶乘, ABS()求绝对值,主要验证,头文件中声明了函数,在cpp文件里,加上头文件,在main函数后面定义声明的函数是可以的 ,
*这个头文件只是函数的声明,具体实现在练习6.8.cpp里面 
*作者:Nick Feng 
*邮箱:nickgreen23@163.com 
*/

#ifndef CHAPTER_6_H
#define CHAPTER_6_H

#include <iostream>

using namespace std;
int fact(int);
void fact1();
void ABS();
#endif

练习6.8

/*
*练习6.8 
*日期:2015/6/9
*问题描述:练习6.8:编写一个名为Chapter6.h的头文件,令其包含6.1节练习(第184页)中的函数声明。
*功能; fact(),fact1()求阶乘, ABS()求绝对值,主要验证,头文件中声明了函数,在cpp文件里,加上头文件,在main函数后面定义声明的函数是可以的 
*作者:Nick Feng 
*邮箱:nickgreen23@163.com 
*/
#include <iostream>
#include <stdexcept>
#include "chapter6.h"

using namespace std;

int main()
{
    cout << fact(6) << endl;
    fact1();
    ABS();
    return 0;
}

int fact(int val)
{
    int Result = 1;
    if (val == 0) 
        Result = 1;
    else if (val > 0)
        {
         for (; val > 0; --val)
              Result *= val;
        }
    else Result = 9999;
    return Result;
}

void fact1()
{
    cout << "input a number(stop with 100): " << endl;
    int val;
    while (cin >> val && val != 100)
    {
    if(val > 0)
    {
        int Result = 1;
        for (int j = val; j > 0; --j)
            Result *= j;
        cout << "The result is: " << Result << endl;
    }

    if (val == 0)
        cout << "The result is: 1" << endl;
    if (val < 0)
        {
            try{
                throw runtime_error("Warning : val can not be less than zero !!!");
            }catch(runtime_error err)
            {
                cout << err.what() << endl;
            }
        }
    }
}

void ABS()
{
    cout << "Input a number(stop wiht 101): " << endl;
    int val;
    while (cin >> val && val != 101)
    {
        if (val >= 0)
            cout << "The absolute value is: " << val << endl;
        else cout << "The absolute value is: " << -val << endl;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值