练习6.1
实参和形参的区别:
- 实参存在于主调函数中,形参存在于被调函数中。
- 实参用于初始化形参,实参必须有确定的值,而形参是一个虚拟变量,而且实参一定会被初始化。
- 实参的实际值值可以由用户/程序员来决定,而形参不代表任何具体值。
练习6.2
(a) 错误:返回的变量是s,类型是string,而函数定义的返回类型为int。
更改后如下所示:
string f1()
{
string s;
return s;
}
(b) 有2种改法:
//有返回值
int f2(int i)
{
return i;
}
//不返回任何值
void f2(int i)
{
}
(3) 重复的参数名,更改后:
int calc(int v1, int v2)
{
}
(d) 函数体应该用花括号括起来
double square(double x)
{
return x * x;
}
练习6.3
注意考虑int的范围问题,比如val=99,它的阶乘太大,所以int覆盖不了,下面代码没有考虑这个问题。
#include <iostream>
using namespace std;
#include <string>
#include<vector>
int fact(int val)
{
int rec = 1;
while (val > 1) {
rec *= val--;
}
return rec;
}
int main(){
cout << "please enter a number greater than 1: ";
int x = 0;
while (cin >> x) { //确保有输入
if (x >= 1)
cout << "the fact is: " << fact(x) << endl;
else { //x为0或者负数的情况下
cout << "Wrong number, please enter a new number" << endl;
continue; //碰到小于1的数字,重新开始循环
}
}
}
练习6.4
与练习6.3答案一致。
练习6.5
double absolute(double val)
{
double rec = 1;
if (val >= 0)
rec = val;
else
rec = -val;
return rec;
}
int main(){
cout << "please enter a number: ";
double x = 0;
while (cin >> x)
cout << "the absolute is: " << absolute(x) << endl;
}