目前学习导航地位的相关知识C++是绕不开的编程语言,我使用的书籍是《C++ Primer Plus》
针对于书中第七章函数模块的复习题做如下笔记。
1.下面是一个结构声明
struct box
{
char maker[40]
float height;
float width;
float length;
float volume;
};
a.编写一个函数,按值传递box结构,并显示每个成员的值
b.编写一个函数,传递box结构的地址,并将volume成员设置为其他三位长度的乘积
c.编写一个使用这两个函数的简单程序
答:
// 按值传递
/* 结构是设计变量类型和命名的一种方式
在后续函数中可以调用以句点的形式
当然也有别的方式*/
#include <iostream>
struct box
{
char maker[40];
float height;
float width;
float length;
float volume;
};
box multiply(box x);
void show_name(box L);
int main()
{
using namespace std;
box result;
cout << "输入作者: ";
cin.get(result.maker, 40);
cout << "输入高度: ";
cin >> result.height;
cout << "输入宽度: ";
cin >> result.width;
cout<< "输入长度: ";
cin >> result.length;
cout<<"maker:"<<result.maker<<endl;
box result2 = multiply(result);
show_name(result2);
return 0;
}
box multiply(box x)
{
box volume1;
volume1.height = x.height;
volume1.length = x.length;
volume1.width = x.width;
volume1.volume = x.height*x.width*x.length;
return volume1;
};
void show_name(box L)
{
using namespace std;
cout<<"height:"<<L.height<<"cm\n"
<<"width:"<<L.width<<"cm\n"
<<"length:"<<L.length<<"cm\n"
<<"volume:"<<L.volume<<"cm^3";
}
// 按结构传递
/* 指针常量不可变所以用const修饰符
*表示变量指针,结构地址&表示 ->地址赋值 */
struct box
{
char maker[40];
float height;
float width;
float length;
float volume;
};
void multiply(box *const x);
void show_name(const box *L);
int main()
{
using namespace std;
box result;
cout << "输入作者: "; //输出
cin.get(result.maker, 40); //输入
cout << "输入高度: ";
cin >> result.height;
cout << "输入宽度: ";
cin >> result.width;
cout<< "输入长度: ";
cin >> result.length;
cout<<"maker:"<<result.maker<<endl;
multiply(&result);
show_name(&result);
return 0;
}
void multiply(box *const x)//const修饰指针可以改变值但不能改变变量
{
using namespace std;
x->volume = x->height * x->width * x->length;
};
void show_name(const box *L)//修饰指针变量指向的值,指针变量可以更改但是值不能更改
{
using namespace std;
cout<<"height:"<<L->height<<"cm\n"
<<"width:"<<L->width<<"cm\n"
<<"length:"<<L->length<<"cm\n"
<<"volume:"<<L->volume<<"cm^3";
}