第7章 函数新
- 格式:ppt
- 大小:568.50 KB
- 文档页数:101


第七章函数题目00What is the difference between a parameter and an argument?形参和实参有什么区别?【解答】形参是在函数定义的形参表中进行定义,是一个变量,其作用域为整个函数。
而实参出现在函数调用中,是一个表达式。
进行函数调用时,用传递给函数的实参对形参进行初始化。
题目01Indicate which of the following functions are in error and why. Suggesthow you might correct the problems.下列哪些函数是错误的?为什么?请给出修改意见。
(a) int f() {string s;// ...return s;}(b) f2(int i) { /* ... */ }(c) int calc(int v1, int v1) /* ... */ }(d) double square(double x) return x * x;【解答】(a)是错误的。
因为函数头中所定义的返回值类型为int,return语句世纪返回的表达式的类型为string,两个类型不同,而string类型又不能隐式转换为int类型。
可修改为:string f(){string s;//…Return s;}(b)是错误的。
因为该函数定义中没有指定返回类型,在标准C++中,定义函数时不指定返回类型是非法的。
可修改为:Int f2(int i){/*…*/}(c)是错误的。
缺少括住函数体在左花括号,而且两个形参不应该同名。
可修改为:Int caic(int v1,intv2){/*…*/}(d)是错误的。
缺少括住函数体的一对花括号。
可修改为:Double square(double x){return x*x;}题目02Write a program to take two int parameters and generate the result ofraising the first parameter to the power of the second. Write a programto call your function passing it two ints. Verify the result.编写一个带有两个int 型形参的函数,产生第一个参数的第二个参数次幂的值。