4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

2点の空間座標の距離を計算するサンプル

Posted at

#説明
空間座標(x, y, z)を2点指定すると、距離を計算し表示します。

##ソースコード

SpaceCalc.cpp
/*
	三次元座標2点を入力すると、
	距離を弾き出す
*/
#include <iostream>
#include <cmath>
using namespace std;

//座標クラス
class coordinate{
public:
	double m_x,m_y,m_z;
	coordinate(double x, double y, double z);
};
//constructor.
coordinate::coordinate(double x, double y, double z){
	m_x = x;
	m_y = y;
	m_z = z;
}

//入力部分。引数には表示したい案内文。
coordinate input(const string& message){
	double x, y, z;
	cout << message << "x:" << flush;
	cin >> x;
	cout << "y:" << flush;
	cin >> y;
	cout << "z:" << flush;
	cin >> z;
	return coordinate(x,y,z);
}

//計算部分
double SpaceCalc(const coordinate& z1, const coordinate& z2){
	return sqrt(pow(z1.m_x - z2.m_x, 2) + pow(z1.m_y - z2.m_y, 2) + pow(z1.m_z - z2.m_z, 2));
}

int main(){
	coordinate cd1 = input("ひとつ目の座標を入力してください ");
	coordinate cd2 = input("ふたつ目の座標を入力してください ");
	cout << "二つの座標点の距離は " << SpaceCalc(cd1, cd2) << "です" << endl;
}

##makefile

makefile
.PHONY: SpaceCalc

SpaceCalc:
	g++ -o SpaceCalc SpaceCalc.cpp
4
1
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?