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
- C++Primer第五版 6.1节练习
- C++Primer 第五版 1.1节练习
- C++Primer第五版 1.3节练习
- C++Primer第五版 1.6节练习
- C++Primer第五版 2.4节练习
- C++Primer第五版 3.1节练习
- C++Primer第五版 4.2节练习
- C++Primer第五版 4.3节练习
- C++Primer第五版 4.4节练习
- C++Primer第五版 4.6节练习
- C++Primer第五版 4.7节练习
- C++Primer第五版 4.8节练习
- C++Primer第五版 4.9节练习
- C++Primer第五版 4.5节练习
- C++Primer第五版 5.1节练习
- C++Primer第五版 5.2节练习
- C++Primer第五版 6.4节练习
- C++Primer第五版 6.6节练习
- Hashtable&HashMap
- 我用闲言碎语,脱掉了你的外衣。
- 【读书笔记】iOS-对象初始化
- 基本常识
- 【特种兵PPT教程】如何用麦肯锡的金字塔原理做好PPT的“前戏”?
- C++Primer第五版 6.1节练习
- 2015年9月14日-学习笔记
- ios开发 -新浪微博(4)封装item 添加分类
- leetcode 57: Insert Interval
- 面向对象设计原则和创建SOLID应用的5个方法
- C++Primer第五版 6.1.1节练习
- 深入认识Tigase XMPP Server
- 学习资料(2)-前端入门
- C++Primer第五版 6.1.2节练习