C++学习(函数模块)

目前学习导航地位的相关知识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";
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值