我的代码:
#include "stdafx.h"
#include <vector>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
typedef pair<int,int> point;
int numTorres, numEdificios;
vector<point> towervec;
vector<point> skyvec;
typedef vector<point>::const_iterator tower_iter;
typedef vector<point>::const_iterator sky_iter;
int noofpaths = 0;
int findslope(const point & i, const point & j, const point & k) {
int dx, dy, dx1, dy1;
dx = j.first - i.first;
dy = j.second - i.second;
int a = dy / dx;
dx1 = k.first - i.first;
dy1 = k.second - i.second;
int b = dy1 / dx1;
if(a != b) {
int length1 = (j.first - i.first) * (j.first - i.first) + (j.second - i.second) * (j.second - i.second);
int length2 = (k.first - i.first) * (k.first - i.first) + (k.second - i.second) * (k.second - i.second);
if(length1 < length2) {
noofpaths++;
}
}
return noofpaths;
}
int main() {
int T;
int n, m;
cout << "enter the test cases" << endl;
cin >> T;
while(T--) {
cout << "towers and skyscrapers" << endl;
cin >> n >> m;
for(int i = 0; i < n; i++) {
point p;
cin >> p.first >> p.second;
towervec.push_back(p);
skyvec.push_back(p);
}
for(int i = 0; i < m; i++) {
point p;
cin >> p.first >> p.second;
skyvec.push_back(p);
}
for(tower_iter i = towervec.begin(); i != towervec.end(); i++) {
for(tower_iter j = i + 1; j != towervec.end(); j++) {
for(sky_iter k = skyvec.begin(); k != skyvec.end(); k++) {
int dx, dy;
noofpaths = findslope(*i, *j, *k);
cout << noofpaths;
}
}
}
}
return 0;
}
如何克服除零误差。如果dx = 0或dy = 0或两者都等于零则代码中断。
如何解决此错误...例如取点 i = -1,-1 j = 1,-1,k-1,-1。我想知道3点是否共线。
答案 0 :(得分:3)
设置if条件以检查变量是否为0,从而将divide语句的变量设置为0。
答案 1 :(得分:0)
使用叉积,对于平行向量,它为零。
#include <iostream>
#include <utility>
using namespace std;
typedef pair<int,int> point;
int SegmentsAreParallel(const point & i, const point & j, const point & k)
{
int dx1, dy1, dx2, dy2;
dx1 = j.first - i.first;
dy1 = j.second - i.second;
dx2 = k.first - i.first;
dy2 = k.second - i.second;
return dx1 * dy2 - dy1 * dx2 == 0;
}
int main()
{
point p1(0, 0);
point p2(1, 1);
point p3(2, 2);
point p4(-1, -1);
point p5(1, -1);
point p6(0, 10);
point p7(0, 100);
point p8(10, 0);
point p9(100, 0);
cout << SegmentsAreParallel(p1, p2, p3) << endl;
cout << SegmentsAreParallel(p1, p2, p4) << endl;
cout << SegmentsAreParallel(p1, p2, p5) << endl;
cout << SegmentsAreParallel(p1, p6, p7) << endl;
cout << SegmentsAreParallel(p1, p8, p9) << endl;
cout << SegmentsAreParallel(p1, p6, p9) << endl;
return 0;
}
输出(ideone):
1
1
0
1
1
0