ページ 11

二点間の角度

Posted: 2008年8月28日(木) 11:02
by 西村
 を、計算するプログラムを作る練習をしていたのですが、何故かしらコンパイラは通るのにいざ実行すると一つ目の座標のxを入力する段で『問題が発生したため終了します』とパソコンから言われて実行出来ません。これは僕のプログラムに欠陥があるからなのか、パソコンがおかしいのか、どちらなのでしょうか?とりあえず、以下がプログラムの内容です。
#include <stdio.h>
#include <math.h>

typedef struct{
  double  x;
  double  y;
}Pos;

int main(void){

  Pos  pos1,  pos2;
  double  ta, rad, dir;

  puts("座標を二つ入力してください");
  printf("X1:");  scanf("%lf", pos1.x);
  printf("Y1:");  scanf("%lf", pos1.y);
  printf("X2:");  scanf("%lf", pos2.x);
  printf("Y2:");  scanf("%lf", pos2.y);

  ta = sqrt((pos1.y - pos2.y) * (pos1.y - pos2.y)) / sqrt((pos1.x - pos2.x) * (pos1.x - pos2.x));
  rad = atan(ta);
  dir = rad / (3.14159265358979 * 180.0);

  printf("二点間の角度は%fです", dir);

  return(0);
}
 あと、角度の出し方自体も色々サイトを見ながら作ったのですが、不安なのでそちらのほうも出来ればお願いします。
 最近雷ばっかりでパソコンつけるの恐いです…

Re:二点間の角度

Posted: 2008年8月28日(木) 11:10
by toyo
scanfの引数はポインタになります。
scanf("%lf", pos1.x);

scanf("%lf", &pos1.x);
ですね
以下同様

Re:二点間の角度

Posted: 2008年8月28日(木) 11:17
by 御津凪
角度の出し方はたしか、
rad = atan2(pos2.y - pos1.y,pos2.x - pos1.x);
でも、角度が出せたかと思います。
(こちらの方が平方根を使わないので処理は早いはず)

Re:二点間の角度

Posted: 2008年8月28日(木) 11:18
by box
>   ta = sqrt((pos1.y - pos2.y) * (pos1.y - pos2.y)) / sqrt((pos1.x - pos2.x) * (pos1.x - pos2.x));

分子・分母とも、「2乗して平方根を計算」していますが、
意味がありますか?
単に、

    ta = (pos1.y - pos2.y) / (pos1.x - pos2.x);

ではダメでしょうか?
なお、分子がゼロ(つまり、2点のx座標が同じ)の場合を
考慮する必要があります。

Re:二点間の角度

Posted: 2008年8月28日(木) 11:19
by toyo
sqrt((pos1.y - pos2.y) * (pos1.y - pos2.y))

(pos1.y - pos2.y)
と同じ値になります。
dir = rad / (3.14159265358979 * 180.0);

dir = rad * 180.0 / 3.14159265358979;
です

Re:二点間の角度

Posted: 2008年8月28日(木) 11:21
by toyo
>sqrt((pos1.y - pos2.y) * (pos1.y - pos2.y))
>は
>(pos1.y - pos2.y)
>と同じ値になります。

同じじゃないですね
絶対値になります。

Re:二点間の角度

Posted: 2008年8月28日(木) 11:53
by 西村
 皆様素早い返答ありがとうございます。

> rad = atan2(pos2.y - pos1.y,pos2.x - pos1.x);

 知りませんでした…早速導入させていただきました。

> ta = (pos1.y - pos2.y) / (pos1.x - pos2.x);
> ではダメでしょうか?

 長さなので負にならないように…と考えたのですが、よくよく考えれば無意味ですね…

何にしろ、無事に出せるようになりました。ありがとうございました!