Q我如何从函数中返回多个值?
A有几种方法可以做到这一点。(这些示例显示了假设的极坐标到直角坐标转换函数,它们必须同时返回 xx和 yy坐标。)
#include <math.h> polar_to_rectangular(double rho, double theta, double *xp, double *yp) { *xp = rho * cos(theta); *yp = rho * sin(theta); } ... double x, y; polar_to_rectangular(1., 3.14, &x, &y);
struct xycoord { double x, y; }; struct xycoord polar_to_rectangular(double rho, double theta) { struct xycoord ret; ret.x = rho * cos(theta); ret.y = rho * sin(theta); return ret; } ... struct xycoord c = polar_to_rectangular(1., 3.14);
polar_to_rectangular(double rho, double theta, struct xycoord *cp) { cp->x = rho * cos(theta); cp->y = rho * sin(theta); } ... struct xycoord c; polar_to_rectangular(1., 3.14, &c);(此技术的另一个示例是 Unix 系统调用 statstat.)