您的位置:首页 > 其它

CH6-1 结构赋值 做函数参数 做函数返回值

2009-12-22 11:35 127 查看
7.1 7.2 做函数参数 做函数返回值


#include <stdio.h>


#include <stdlib.h>


//结构变量初始化,赋值,做函数参数,做函数返回值


struct Point{


int x;


int y;


}; //声明,不会分配内容空间




struct Point createPoint(int x, int y){


struct Point pt;


pt.x = x;


pt.y = y;


return pt;


}


//矩形 包含了两个成员均为 Point变量


struct Rectangle{


struct Point pt1;


struct Point pt2;


};


//结构变量做形参


struct Rectangle createRectangle(struct Point pt1, struct Point pt2){


struct Rectangle screen;


screen.pt1 = pt1;


screen.pt2 = pt2;


return screen;


}




struct Point addPoint(struct Point pt1, struct Point pt2){


pt1.x += pt2.x;


pt1.y += pt2.y;


return pt1;


}




int ifInside(struct Point pt, struct Rectangle rt){


return pt.x >= rt.pt1.x && pt.x < rt.pt2.x &&


pt.y >= rt.pt1.y && pt.y < rt.pt2.y;


}




int getArea(struct Rectangle rt){


int length = (rt.pt2.x>rt.pt1.x)?(rt.pt2.x-rt.pt1.x) : (rt.pt1.x - rt.pt2.x);


int width = (rt.pt2.y>rt.pt1.y)?(rt.pt2.y-rt.pt1.y) : (rt.pt1.y - rt.pt1.y);


return length * width;


}




int main(int argc, char** argv) {


struct Point pt1 = {10, 10};//声明结构变量,分配空间,并赋初值


struct Point pt2 = {20, 20};


//==================


struct Point pt3 = addPoint(pt1, pt2);


struct Rectangle screen = createRectangle(pt1, pt3);


printf("area(pt1, pt3) = %d\n", getArea(screen));


printf("pt1.x = %d, pt1.y = %d\n", pt1.x, pt1.y);//传值,不修改实参的值


//==============


struct Point middlePT = createPoint((int)((pt1.x + pt3.x)/2),


(int)((pt1.y + pt3.y)/2));


if(ifInside(middlePT, screen))


printf("middlePT[%d, %d] is inside of screen(pt1[%d, %d], pt3[%d, %d])\n",


middlePT.x, middlePT.y, pt1.x, pt1.y, pt3.x, pt3.y);


else


printf("middle point is not inside of screen\n");


return (EXIT_SUCCESS);


}

7.3
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: