C++Primer第五版 6.1节练习

来源:互联网 发布:pin破解wifi软件 编辑:程序博客网 时间:2024/05/16 09:13

练习6.1;实参和形参的区别是什么?
练习6.2:请指出下列函数哪个有错误,为什么?应该如何修改这些错误呢?

(a). int f(){ string s; //… return s;}(b) f2(int i){/*…*/}(c) int calc(int v1, int v2) /*…*/ }(d) double square(double x) return x*x;

练习6.3:编写你自己的fact函数,上机检查是否正确。

练习6.4:编写一个与用户交互的函数,要求用户输入一个数字,计算生成该数字的阶乘。在main函数中调用该函数。

练习6.5:编写一个函数输出实参的绝对值。

答:练习6.1:
实参是形参的初始值。编译器能以任意可行的顺序对实参求值。实参的类型必须与对应的形参类型匹配。

练习6.2:修正后

(a)string f(){ string s; //… return s;}(b)int  f2(int i){/*…*/}(c) int calc(int v1, int v2) {/*…*/ }(d) double square(double x) {return x*x;}

练习6.3 – 6.5见云盘程序。

/**练习6.3 *2015/6/8 *问题描述:练习6.3:编写你自己的fact函数,上机检查是否正确。 *功能:阶乘*作者:Nick Feng *邮箱:nickgreen23@163.com * */#include <iostream>#include <stdexcept>using namespace std;void Fact(int val){    int Result = 1;    if (val > 0)        {            int j = 0;            for (j = val; j > 0; --j)                Result *= j;                cout << "The result is: "  << Result << endl;           }    if (val == 0)         {         Result = 1;         cout << "The result is: "  << Result << endl;        }    if (val < 0)         {            try{                throw runtime_error("wrong inputing : val can not less than zero !!!");                //装个X,val<0时抛出一个异常,捕获异常                 }catch(runtime_error err){                cout << err.what() << endl;                     }        }   }int main(){    int val;    while (cin >> val)        Fact(val);     return 0;} 

练习6.4

/**练习6.4*2015/6/8 *问题描述:练习6.4:编写一个与用户交互的函数,要求用户输入一个数字,计算生成该数字的阶乘。在main函数中调用该函数。 *功能:阶乘*作者:Nick Feng *邮箱:nickgreen23@163.com * */#include <iostream>#include <stdexcept>using namespace std;void Fact(){    int val;    cout << "input a number: " << endl;    while (cin >> val)    {        if (val > 0)         {            int Result = 1;            for (;val > 0; --val)                Result *= val;            cout << "The result is: " << Result << endl;         }        else if (val == 0)            cout << "The result is: 1" << endl;            else                 try{                    throw runtime_error("wrong inputing :val can not be less than zero!!!");                } catch(runtime_error err){                        cout << err.what() << endl;                }    } }int main(){    Fact();    return 0;}

练习6.5

/**练习6.5*2015/6/8 *问题描述:练习6.5:编写一个函数输出实参的绝对值。*功能:求绝对值 *作者:Nick Feng *邮箱:nickgreen23@163.com * */#include <iostream>using namespace std;void ABS(){    int val;    cout << "input a number :" << endl;    while (cin >> val)    {        if (val >= 0)             cout << "The absolute value is: " << val << endl;        else cout << "The absolute value is: " << -val << endl;    } }int main(){    ABS();    return 0;}
0 0
原创粉丝点击