首页 > 试题广场 >

下面是一个结构声明: struct box {

[问答题]
下面是一个结构声明:
struct box
{
char maker[40];
float height;
float width;
float length;
float volume;
};
a. 编写一个函数,按值传递box结构,并显示每个成员的值。
b. 编写一个函数。传递box结构的地址,并将volume成员设置为其他三维长度的乘积。
c. 编写一个使用这两个函数的简单程序。
// c++中函数参数传递方式有三种
// 1.按值传递--首先计算出实参表达式的值,接着给对应的形参分配一个存储空间,
// 该空间的大小等于该形参类型的,求出实参表示式的值,存入到形参变量分配的存储空间,
// 成为形参变量的处置,供被调用函数执行时使用。
// 2.地址传递
// 地址传递和按值传递的不同在于,它把实参的存储地址传递给对应的形参,
// 从而使得形参指针和实参指针指向同一个地址。
// 因此,被调用函数中形参指针所指向的地址中内容的任何改变都会影响到实参
// 3.引用传递
// 按值传递方式容易理解,但形参值的改变不能对实参产生影响。
// 地址传递方式虽然可以使得形参的改变对相应的实参有效,但如果在函数中反复利用指针进行间接访问,
// 会使程序容易产生错误且难以阅读。
// 如果以引用为参数,则既可以使得对形参的任何操作都能改变相应的数据,又使得函数调用显得方便、自然。
// 引用传递方式是在函数定义时在形参前面加上引用运算符“&”。
#include <iostream>
struct box
{
    char maker[40];
    float height;
    float width;
    float length;
    float volume;
};
void value_box(const struct box box1);
void address_box(const struct box * pbox);
void quote_box(const struct box &box1);
int main(int argc, char const *argv[])
{
    struct box box1;
    box1.height = 12.2;
    struct box * pbox1 = &box1;
    value_box(box1);
    address_box(pbox1);
    quote_box(box1);
    return 0;
}
void value_box(const struct box box1) 
{
    std::cout << box1.height << std::endl;
}
void address_box(const struct box * pbox)
{
    std::cout << pbox->height << std::endl;
}
void quote_box(const struct box &box1) 
{
    std::cout << box1.height << std::endl;
}
发表于 2020-03-11 11:30:33 回复(0)
#include<iostream>
using namespace std;
void show(struct box B);
void make(struct box B);

struct box
{
    char maker[40];
    float height;
    float width;
    float length;
    float volume;
};

int main()
{
    struct box B;
    cout << "请输入一串字符:";
    cin.get(B.maker, 40).get();
    cout << "请分别输入height、width和length的值(用空格隔开):";
    cin >> B.height >> B.width >> B.length;
    show(B);
    make(B);
    return 0;
}

void show(struct box B)
{
    cout << "maker = {" << B.maker << "}\n" ;
    cout << "height = " << B.height << endl;
    cout << "width = " << B.width << endl;
    cout << "length = " << B.length << endl;
}

void make(struct box B)
{
    B.volume = B.height * B.width * B.length;
    cout << "volume的值为:" << B.volume <<endl;
}
发表于 2019-08-30 10:48:28 回复(0)
#include <iostream>
#include <Windows.h>
using namespace std;
struct box
{
 char maker[40];
 float height;
 float width;
 float length;
 float volume;
};
void show(struct box B)
{
 cout << "maker = " << B.maker << endl
  << "height = " << B.height << endl
  << "width = " << B.width << endl
  << "length = " << B.length << endl
  << "volume = " << B.volume << endl;
}
void make(struct box *B)
{
 B->volume = B->height*B->length*B->width;
}
int main()
{
 struct box B;
 cout << "请输入一个字符串,送到该结构体的maker成员里" << endl;
 cin >> B.maker;
 cout << "请输入3个数字,这三个数字分别为height、width和length" << endl;
 cin >> B.height >> B.length >> B.width;
 make(&B);
 cout << "接下来会显示里面的内容" << endl;
 show(B);
 system("pause");
}

发表于 2019-06-21 10:55:06 回复(0)