第13回の課題の解説

課題 1 (長方形の面積)
課題 2 (長方形が原点を内部に含むか)

課題 1 (長方形の面積)

まず, 構造体を使わずに, これまでの知識だけでプログラムを書くとこんな感じ:
#include <stdio.h> #include <stdlib.h> int main(void){ char line[256]; double x1, y1, x2, y2; double area; gets(line); x1 = atof(line); gets(line); y1 = atof(line); gets(line); x2 = atof(line); gets(line); y2 = atof(line); area = (x2 - x1) * (y1 - y2); printf("%f\n", area); return 0; }
二組の点の座標の大小関係が決まっているので (x2 > x1 かつ y1 > y2) 面積を求めるのは簡単である.

次に, 教科書P.277のプログラムを修正して, 構造体を使う方法. 教科書のプログラムにはすでに面積を求める関数が含まれているから, main を修正するだけで大丈夫. main はこうなる:

int main(void){ char line[256]; struct rectangle rect; double area; gets(line); rect.x1 = atof(line); gets(line); rect.y1 = atof(line); gets(line); rect.x2 = atof(line); gets(line); rect.y2 = atof(line); area = calc_area(rect); printf("%f\n", area); return 0; }

課題 2 (長方形が原点を内部に含むか)

こちらも, まずは構造体を使わないプログラム.
#include <stdio.h> #include <stdlib.h> int main(void){ char line[256]; double x1, y1, x2, y2; gets(line); x1 = atof(line); gets(line); y1 = atof(line); gets(line); x2 = atof(line); gets(line); y2 = atof(line); if((x1 <= 0) && (y1 >= 0) && (x2 >= 0) && (y2 <= 0)){ printf("yes\n"); } else { printf("no\n"); } return 0; }
原点を含むかの判定は, 「左上点が第二象限にあり, かつ, 右下点が第四象限にある」 ということと同値だから, 上のように判定すればよい. さらに巧妙な方法としては, 「左上点と右下点でx座標の符号が逆」 (y座標についても同様)と考えると, if の判定条件を以下のように書くこともできる:
if((x1 * x2 <= 0) && (y1 * y2 <= 0)){

さいごに, 構造体と関数を使ったプログラム. 関数 include_O は, 長方形 r を引数として受け取り, それが原点を含むなら 1 を, そうでなければ 0 を返す関数である. 関数の定義とmainはこんな感じ (プログラムとして動かすためには, このほかに include や struct rect の定義などが必要である):

int include_O(struct rectangle r){ if((r.x1 * r.x2 <= 0) && (r.y1 * r.y2 <= 0)){ return 1; } else { return 0; } } int main(void){ char line[256]; struct rectangle rect; int answer; gets(line); rect.x1 = atof(line); gets(line); rect.y1 = atof(line); gets(line); rect.x2 = atof(line); gets(line); rect.y2 = atof(line); answer = include_O(rect); if(answer == 1){ printf("yes\n"); } else { printf("no\n"); } return 0; }