结构体作为函数的参数

来源:互联网 发布:32寸海信网络液晶电视 编辑:程序博客网 时间:2024/05/17 04:35

①整个结构体作为函数的参数

实例:

#include <iostream>#include <cmath>using namespace std;struct rect{    float x;    float y;};struct polar{    float distance;    float angle;};polar rect_to_polar(rect rec);void show_polar(polar pol);int main(){    rect rec;    polar pol;    cout << "Enter the x and y values: ";    while(cin >> rec.x >> rec.y)    {        pol = rect_to_polar(rec);        show_polar(pol);        cout << "Next two numbers(q to quit): ";    }    return 0;}polar rect_to_polar(rect rec){    polar pol;    pol.distance = sqrt(rec.x * rec.x + rec.y * rec.y);    pol.angle = atan2(rec.y, rec.x);    return pol;}void show_polar(polar pol){    cout << "diatance = " << pol.distance << ", angle = " << pol.angle << " degrees" << endl;}

②结构体的指针作为函数的参数:

实例:

#include <iostream>#include <cmath>using namespace std;struct rect{    float x;    float y;};struct polar{    float distance;    float angle;};void rect_to_polar(rect *p_rect, polar *p_polar);void show_polar(polar *p_polar);int main(){    rect prect;    polar ppolar;    cout << "Enter the x and y values: ";    while(cin >> prect.x >> prect.y)    {        rect_to_polar(&prect, &ppolar);        show_polar(&ppolar);        cout << "Next two numbers(q to eqit): ";    }    return 0;}void rect_to_polar(rect *p_rect, polar *p_polar){    p_polar->distance = sqrt(p_rect->x * p_rect->x + p_rect->y * p_rect->y);    p_polar->angle = atan2(p_rect->y, p_rect->x);}void show_polar(polar *p_polar){    cout << "distance = " << p_polar->distance << ", angle = " << p_polar->angle << endl;}


0 0
原创粉丝点击