Hi nypren!
in your code line 58 is
double dist = sqrt(x*x) + sqrt(y*y);
what could be simplified to
dist = x + y;
I assume, x and y are coordinates within a orthogonal system, in that case the distance of point (x, y) to the origin would be
dist = sqrt(x*x + y*y);
due to Pythagoras.
I myself am new to C++, since two weeks I have VS2010 installed and compiled with success a simple modifcation of an existing program. I made my living with other languages. So I may not answer your question about
struct Coord
{
double x, y;
}; |
But an advice, keep it simple and smart. Less code enhances the readability, reduces the chance for typ0s, and gives you more time for comments (which could be of some help in future). Reading along the tutorial of this site, I took the "Pi by Mote Carlo" as an exercise for myself. Here my suggestion (which confirms the saying, a good FORTRAN programmer may do FORTRAN in any language):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
/* PiRan: Compute Pi using Monte Carlo Method */
#include <iostream>
using namespace std;
void main()
{
unsigned long n, t, hit(0), x, y, Rsqr=RAND_MAX*RAND_MAX;
char a;
once_more:
cout << "Please enter numbers of throws: "; cin >> n;
t = n; /* keep for later use */
while (n-->0) {
x = rand(); y = rand();
hit += x*x+y*y < Rsqr ? 1 : 0;
}
cout << "Pi is approximately " << 4.0 * hit / t << endl;
ask_again:
cout << "Try it again(Y/N)? ";
cin >> a;
if (a == 'Y' || a == 'y') goto once_more;
// if (a != 'N' && a != 'n') goto ask_again;
}
|
The main structure is input data - compute - output result. The jump back to do it once more is already a concession to the pretentious target group. (The jump to label
ask_again: gives the chance for an endless loop as I do not yet fully understand cin.)
In the repeating loop I kept only the necessary, I even compare the squared values to avoid time consuming square root
and avoid the need of real variables, approximating transcendental Pi by inters only.
Your task to use
struct Coord { double x, y; }; |
looks like object oriented programming, where you have a Point which may tell you his Coordinates, and if it's a good Point it may even tell you the distance to the origin (if the programmer new the correct formula). Those concepts are not new but still a cultural clash for me.
Please let us know how your solved the task using
struct Coord { double x, y; }; |