448,813 Members | 1,669 Online Need help? Post your question and get tips & solutions from a community of 448,813 IT Pros & Developers. It's quick & easy.

# C++ project help Generating variables.

 P: n/a Basicly i have to make a program that calculates the distance between x and y points in 2d space. the code basicly goes like this 1. User says how many points they have (max of 10) 2. User enters points 3. Using sqrt( (x2-x1)^2 + (y2-y1)^2) ) It calculates the distance between 2 points 4. It displays the length between the first and last point. My problem is how do i accept the data. im not sure how to vary the number of inputs or how to declare the variables. like say the user wants 6 points how do i let the program know only to ask the user for 6 points. and then how do i do the same calculation for each of those points. i tried using a while loop and heres my code so far. #include ; #include using namespace std; double length(double xa,double xb,double ya,double yb) { double length=0; length=sqrt(((xb-xa)*(xb-xa))+((yb-ya)*(yb-ya))); return (length); } int main() int points=0; int ans=0; double length(double,double,double,double) double xa=0; double xb=0; double ya=0; double yb=0; cout <<"How many points would you like to input (Max 10)?\n\n"; cin >>points; while (points 1) { cout <<"Please enter an x value\n"; cin >>xa; cout <<"Please enter a y value\n"; cin >>ya; cout <<"Please enter an x value\n"; cin >>xb; cout <<"Please enter a y value\n"; cin >>yb; ans=ans+length(xa,xb,ya,yb) points=points-1; } return (0); Im using VC++ i know the codes a little crappy but hey thats what help is for right :) Thanks in advance to any genius who can sort this mess out. Nov 27 '06 #1
28 Replies

 P: n/a On Nov 27, 8:07 am, "Nutkin" #include #include nrPoints; for (int i = 0; i < nrPoints; ++i) // For-loops are nice, but can use while too { double x, y; std::cout << "Enter x: "; std::cin >x; std::cout << "Enter y: "; std::cin >y; points.push_back(std::make_pair(x,y)); // add the point to the collection } // Calculate distance return 0; } Then you can access the points just like this: points.first // The x-value of the third point (starts from 0) points.second // The y-value of the second point To get the distance I'd do something like this: for (int i = 0; i < nrPoints - 1; ++i) // Notice nrPoints -1 { ans += length(points[i].first, points[i+1].first, points[i].second, points[i+1].second) } You could also use two vectors, one for x- and one for y-values. -- Erik Wikstöm Nov 27 '06 #2

 P: n/a er****@student.chalmers.se I thin you want to use a container-class to store the points in,something like this:#include #include #include

 P: n/a er****@student.chalmers.se wrote: On Nov 27, 8:07 am, "Nutkin" #include #include nrPoints; for (int i = 0; i < nrPoints; ++i) // For-loops are nice, but can use while too { double x, y; std::cout << "Enter x: "; std::cin >x; std::cout << "Enter y: "; std::cin >y; points.push_back(std::make_pair(x,y)); // add the point to the collection } // Calculate distance return 0; } Then you can access the points just like this: points.first // The x-value of the third point (starts from 0) points.second // The y-value of the second point To get the distance I'd do something like this: for (int i = 0; i < nrPoints - 1; ++i) // Notice nrPoints -1 { ans += length(points[i].first, points[i+1].first, points[i].second, points[i+1].second) } You could also use two vectors, one for x- and one for y-values. -- Erik Wikstöm I think thats a bit over my head but i can see where you are coming from. So i shall study it a bit more and see if i can get away with using it. But we havnt been taught vectors yet so im not sure if it will be valid. Thanks so much for giving me some options im gonna have a play about with ti now. If anyone has a more basic idea would be awesome.. Nov 27 '06 #4

 P: n/a Nutkin wrote: Basicly i have to make a program that calculates the distance between x and y points in 2d space. the code basicly goes like this 1. User says how many points they have (max of 10) 2. User enters points 3. Using sqrt( (x2-x1)^2 + (y2-y1)^2) ) It calculates the distance between 2 points 4. It displays the length between the first and last point. My problem is how do i accept the data. im not sure how to vary the number of inputs or how to declare the variables. like say the user wants 6 points how do i let the program know only to ask the user for 6 points. and then how do i do the same calculation for each of those points. i tried using a while loop and heres my code so far. Your code looks to be on the right track, but I would rethink using an int for the ans variable. Should it not be capable of holding values like 0.5 too? For checking the users input, you could use an infinite loop and break out of it when you have checked the input is valid: int points = 0; // for loop continues until number of points is valid for (;;){ std::cout <<"How many points would you like to input (Max 10)? : "; std::cin >points if ((points < 2) || (points 10)){ std::cout << "number of points has to be between 2 and 10\n"; } else { break; } } you could also use a while loop or a do loop instead of course. regards Andy Little Nov 27 '06 #5

 P: n/a kwikius wrote: Nutkin wrote: Basicly i have to make a program that calculates the distance between x and y points in 2d space. the code basicly goes like this 1. User says how many points they have (max of 10) 2. User enters points 3. Using sqrt( (x2-x1)^2 + (y2-y1)^2) ) It calculates the distance between 2 points 4. It displays the length between the first and last point. My problem is how do i accept the data. im not sure how to vary the number of inputs or how to declare the variables. like say the user wants 6 points how do i let the program know only to ask the user for 6 points. and then how do i do the same calculation for each of those points. i tried using a while loop and heres my code so far. Your code looks to be on the right track, but I would rethink using an int for the ans variable. Should it not be capable of holding values like 0.5 too? For checking the users input, you could use an infinite loop and break out of it when you have checked the input is valid: int points = 0; // for loop continues until number of points is valid for (;;){ std::cout <<"How many points would you like to input (Max 10)? : "; std::cin >points if ((points < 2) || (points 10)){ std::cout << "number of points has to be between 2 and 10\n"; } else { break; } } you could also use a while loop or a do loop instead of course. regards Andy Little Ive now been told i must use arrays ahhh i hate my uni. Nov 27 '06 #6

 P: n/a On Nov 27, 10:28 am, "Nutkin"

 P: n/a On 27 Nov 2006 02:52:59 -0800, "er****@student.chalmers.se" On Nov 27, 10:28 am, "Nutkin" Ive now been told i must use arrays ahhh i hate my uni. Then first read in the number of points wanted then dynamicallyallocate the array using new, then the rest should be quite like what'salready discussed. Don't forget to deallocate the array when you aredone with it (using delete). No need to bo so complex. We know that there will be a maximum of 10 points so allocate a fixed size array big enough to hold 10 points. With small amounts of data there is no need to get into the complexities of dynamic arrays. The OP may not have studied new and delete yet, this assignment seems to be quite simple and likely to be early in the course. rossum Nov 27 '06 #8

 P: n/a On Nov 27, 3:10 pm, rossum

 P: n/a er****@student.chalmers.se wrote in message ... /* """ I thin you want to use a container-class to store the points in, something like this: #include #include #include nrPoints; for (int i = 0; i < nrPoints; ++i){ // For-loops are nice, but can use while too double x, y; std::cout << "Enter x: "; std::cin >x; std::cout << "Enter y: "; std::cin >y; // add the point to the collection points.push_back(std::make_pair(x,y)); } // Calculate distance return 0; } Then you can access the points just like this: points.first // The x-value of the third point (starts from 0) points.second // The y-value of the second point To get the distance I'd do something like this: for (int i = 0; i < nrPoints - 1; ++i){ // Notice nrPoints -1 ans += length(points[i].first, points[i+1].first, points[i].second, points[i+1].second) } You could also use two vectors, one for x- and one for y-values. Erik Wikstöm """ */ You guys (include Steve Pope) are involving way too much complexity (yes, Steve, a pun). You're not trying to hide simplicity from the boss, but, help a starting student. If the OP could use 'vector' (later states (s)he can't), a simple vector of struct would make life easier (in the OPs assignment). // class Point{ public: // same thing struct Point{ double x; double y; Point() : x(0), y(0){} }; { // main() or function std::vector

 P: n/a Nutkin wrote in message ... >Ive now been told i must use arrays ahhh i hate my uni. It's just the ol' "pencil-n-paper before calculator" thing. Since you know the maximum number of elements, you could just set up the array to max, and put the limits in input/output. // #includes here int main(){ std::size_t const sz( 10 ); double X[ sz ] = {0}; double Y[ sz ] = {0}; // - get the max number from user and check for range. - for( std::size_t i( 0 ); i < NumFromUser; ++i ){ cin >X[ i ]; cin >Y[ i ]; if( not cin ){ std::cerr <<"ERROR!"<

 P: n/a Nutkin wrote: Basicly i have to make a program that calculates the distance between x and y points in 2d space. the code basicly goes like this 1. User says how many points they have (max of 10) 2. User enters points 3. Using sqrt( (x2-x1)^2 + (y2-y1)^2) ) It calculates the distance between 2 points 4. It displays the length between the first and last point. Why bother entering all the data points, when you are only going to display the first and last points entered, ignoring the rest? If you made me enter 1000 points, then ignored all but the first and last entry, I'd probably get pissed off. My problem is how do i accept the data. im not sure how to vary the number of inputs or how to declare the variables. like say the user wants 6 points how do i let the program know only to ask the user for 6 points. and then how do i do the same calculation for each of those points. Assuming you want the difference between point 1 and last entered point, just enter/store point 1, then loop through additional points (input, calculate, display, repeat). Only need storage for two points at a time (point 1 and current point) ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups ----= East and West-Coast Server Farms - Total Privacy via Encryption =---- Nov 27 '06 #12

 P: n/a er****@student.chalmers.se . -- Marcus Kwok Replace 'invalid' with 'net' to reply Nov 27 '06 #13

 P: n/a Kevin Handy wrote: Nutkin wrote: Basicly i have to make a program that calculates the distance between x and y points in 2d space. the code basicly goes like this 1. User says how many points they have (max of 10) 2. User enters points 3. Using sqrt( (x2-x1)^2 + (y2-y1)^2) ) It calculates the distance between 2 points 4. It displays the length between the first and last point. Why bother entering all the data points, when you are only going to display the first and last points entered, ignoring the rest? If you made me enter 1000 points, then ignored all but the first and last entry, I'd probably get pissed off. My problem is how do i accept the data. im not sure how to vary the number of inputs or how to declare the variables. like say the user wants 6 points how do i let the program know only to ask the user for 6 points. and then how do i do the same calculation for each of those points. Assuming you want the difference between point 1 and last entered point, just enter/store point 1, then loop through additional points (input, calculate, display, repeat). Only need storage for two points at a time (point 1 and current point) But is it the distance from the first to last point, or the sums of the lengths of discrete disconnected lines, or the length of the line joining each point to the next? The requirements arent clear AFAICS. regards Andy Little Nov 27 '06 #14

 P: n/a BobR You guys (include Steve Pope) are involving way too much complexity (yes,Steve, a pun). You're not trying to hide simplicity from the boss, but, helpa starting student. >If the OP could use 'vector' (later states (s)he can't), a simple vector ofstruct would make life easier (in the OPs assignment).// class Point{ public: // same thingstruct Point{ double x; double y; Point() : x(0), y(0){} }; So... since the language already has complex

 P: n/a Steve Pope wrote in message ... >BobR wrote: >>You guys (include Steve Pope) are involving way too much complexity (yes,Steve, a pun). You're not trying to hide simplicity from the boss, but, help >>a starting student. >>If the OP could use 'vector' (later states (s)he can't), a simple vector ofstruct would make life easier (in the OPs assignment).// class Point{ public: // same thingstruct Point{ double x; double y; Point() : x(0), y(0){} }; So... since the language already has complex >Use what's already there, I say.Steve That's the Point! It is/maybe not there yet for the student just starting arrays. Seems to me that 'x, y' is easier than 'real, imag' for a student at that stage (assuming (s)he isn't a math major ). If the instructor won't accept 'vector', 'complex' would probably be off-limits also. If this were a guy modifying a library for Charles Schwab, I'd say "throw the curve ball to him". For this instance, we need to put the ball on the tee and teach the person to swing the bat. -- Bob R POVrookie Nov 28 '06 #17

 P: n/a BobR Steve Pope wrote in message ... >>So... since the language already has complexNope! complex >>Use what's already there, I say. That's the Point! It is/maybe not there yet for the student just starting arrays. It should definitely be there. Steve Nov 28 '06 #18

 P: n/a Steve Pope wrote in message ... >BobR wrote: >>Steve Pope wrote in message ... >>>So... since the language already has complex>Nope! complex Ah ha, so you admit it wasn't 'built-in'!?! [ sorry - the devil made me do it. ] -- Bob R POVrookie Nov 28 '06 #19

 P: n/a On 2006-11-27 20:41, Marcus Kwok wrote: er****@student.chalmers.se #include . I've always wondered where it was, but never really bothered since I've only seldomn used it outside a map. Thanks. -- Erik Wikström Nov 28 '06 #20

 P: n/a Jim Langston wrote: Well, your program would work with a little modification, but what about now you want to know the average of the distances, etc? You are not storing the points. Two ways, like I said. A dynamic array, or a std::vector. I believe in your case a std::vector would be prefered. Another alternative is a recursive function. (mag_n below). In this case the function call stack is used to store intermediate reults: Also makes gratuitous use of the infamous GOTO :-) regards Andy Little //--------------------------------- #include #include #include // a 2D vector type struct vect{ double x,y; vect():x(0),y(0){} vect (double const & x_in, double const & y_in) :x(x_in),y(y_in){} }; inline vect operator -(vect const & lhs, vect const & rhs) { return vect(lhs.x-rhs.x,lhs.y - rhs.y); } std::istream & operator >>(std::istream & in, vect & pt) { in >pt.x >pt.y; return in; } std::ostream & operator <<(std::ostream & out, vect const & pt) { out <<'(' << pt.x << ','<< pt.y << ')'; return out; } inline double magnitude(vect const & v) { return std::sqrt(v.x * v.x + v.y * v.y); } typedef vect point; double mag_n( point const & p_in, int current_point, int const num_points) { int next_point = current_point + 1; std::cout << "Enter point number " << next_point << " : "; point p; std::cin >p; double result = magnitude( p - p_in); if( next_point < num_points) { result += mag_n(p,next_point, num_points); } return result; } int main() { // the infamous goto... start: std::cout << "Enter num points to input : "; int num_points = 0; std::cin >num_points; std::cout << '\n'; if ((num_points <2) || (num_points 10)){ std::cout << "Error: must be 2 <= num points <=10\n"; goto start; } std::cout << "Enter first point:(syntax x y) : "; point p; std::cin >p; double result = mag_n(p,1, num_points) ; std::cout << "path length = " << result <<'\n'; std::cout << "Do another set of points? (y/n) : "; std::string str; std::cin >str; if ( str.substr(0,1) == "y"){ goto start; } } Nov 28 '06 #21

 P: n/a kwikius wrote in message ... >Also makes gratuitous use of the infamous GOTO :-)Andy Little//---------------------------------int main(){start: // the infamous goto... std::cout << "Enter num points to input : "; int num_points = 0; std::cin >num_points; std::cout << '\n'; if ((num_points <2) || (num_points 10)){ std::cout << "Error: must be 2 <= num points <=10\n"; goto start; } std::cout << "Enter first point:(syntax x y) : "; point p; std::cin >p; double result = mag_n(p,1, num_points) ; std::cout << "path length = " << result <<'\n'; std::cout << "Do another set of points? (y/n) : "; std::string str; std::cin >str; if ( str.substr(0,1) == "y"){ goto start; }} 'goto' gives some C++ programmers 'the bends'! :-} int main(){ // >start: // the infamous goto... while(true){ std::cout << "Enter num points to input : "; int num_points( 0 ); std::cin >num_points; std::cout<< num_points << std::endl; > if( (num_points < 2) || (num_points 10) ){ std::cout << "Error: must be 2 <= num points <=10\n"; // goto start; continue; } // if(!range) std::cout << "Enter first point:(syntax x y) : "; point p; std::cin >p; double result = mag_n(p,1, num_points) ; std::cout << "path length = " << result <<'\n'; std::cout << "Do another set of points? (y/n) : "; std::string str; std::cin >str; std::cout << str < // if ( str.substr(0,1) == "y"){ goto start; } if ( str.substr(0,1) != "y" ){ break; } } // while(1) return 0; } // main() -- Bob R POVrookie Nov 28 '06 #22

 P: n/a BobR wrote: 'goto' gives some C++ programmers 'the bends'! :-} I see. Sincere Apologies for that. OK, now I got rid of the gotos. How about this version? I'm making cool use of exceptions to keep stuff moving in this version. Better now huh? regards Andy Little #include #include #include // a 2D vector type struct vect{ double x,y; vect():x(0),y(0){} vect (double const & x_in, double const & y_in) :x(x_in),y(y_in){} }; inline vect operator -(vect const & lhs, vect const & rhs) { return vect(lhs.x-rhs.x,lhs.y - rhs.y); } std::istream & operator >>(std::istream & in, vect & pt) { in >pt.x >pt.y; return in; } std::ostream & operator <<(std::ostream & out, vect const & pt) { out <<'(' << pt.x << ','<< pt.y << ')'; return out; } inline double magnitude(vect const & v) { return std::sqrt(v.x * v.x + v.y * v.y); } typedef vect point; double mag_n( point const & p_in, int current_point, int const num_points) { int next_point = current_point + 1; std::cout << "Enter point number " << next_point << " : "; point p; std::cin >p; double result = magnitude( p - p_in); if( next_point < num_points) { result += mag_n(p,next_point, num_points); } return result; } // exceptions.. struct good_input{ int n_points; good_input(int n_points_in):n_points(n_points_in){} }; struct quit{ int f(){return 0;}}; int main() { try{ for(;;){ try{ while(1){ int num_points = 0; std::cout << "Enter num points to input : "; std::cin >num_points; std::cout << '\n'; if ((num_points >=2) && (num_points <= 10)){ throw good_input(num_points); } else{ std::cout << "Error: must be 2 <= num points <=10\n"; } } } catch (good_input & e){ int num_points = e.n_points; std::cout << "Enter first point:(syntax x y) : "; point p; std::cin >p; double result = mag_n(p,1, num_points) ; std::cout << "path length = " << result <<'\n'; std::cout << "Do another set of points? (y/n) : "; std::string str; std::cin >str; if ( str.substr(0,1) != "y"){ throw quit(); } } } } catch (quit & e){return e.f();} } Nov 29 '06 #23

 P: n/a kwikius wrote in message <11*********************@h54g2000cwb.googlegroups. com>... >BobR wrote: >'goto' gives some C++ programmers 'the bends'! :-} I see. Sincere Apologies for that. OK, now I got rid of the gotos. Howabout this version? I'm making cool use of exceptions to keep stuffmoving in this version. Better now huh? First 'the bends', now 'the willies'!! >regardsAndy Little#include #include #include struct vect{ // a 2D vector type double x,y; vect():x(0),y(0){} vect (double const & x_in, double const & y_in) :x(x_in),y(y_in){}};inline vect operator -(vect const & lhs, vect const & rhs){ return vect(lhs.x-rhs.x,lhs.y - rhs.y);}std::istream & operator >>(std::istream & in, vect & pt){ in >pt.x >pt.y; return in;}std::ostream & operator <<(std::ostream & out, vect const & pt){ out <<'(' << pt.x << ','<< pt.y << ')'; return out;}inline double magnitude(vect const & v){ return std::sqrt(v.x * v.x + v.y * v.y);}typedef vect point; Why a typedef? Simply rename 'vect' to 'point'. You trying to be cute? Ah, you're 'just pulling my leg'! >double mag_n( point const & p_in, int current_point, int constnum_points){ int next_point = current_point + 1; std::cout << "Enter point number " << next_point << " : "; point p; std::cin >p; double result = magnitude( p - p_in); if( next_point < num_points) { result += mag_n(p,next_point, num_points); } return result;}struct good_input{ // exceptions.. int n_points; good_input(int n_points_in):n_points(n_points_in){} };struct quit{ int f(){return 0;}};int main(){ try{ for(;;){ try{ while(1){ int num_points = 0; std::cout << "Enter num points to input : "; std::cin >num_points; std::cout << '\n'; if ((num_points >=2) && (num_points <= 10)){ throw good_input(num_points); } else{ std::cout << "Error: must be 2 <= num points<=10\n"; } } } **Gross misuse** of exceptions to control normal program flow. It's fun to experiment, but, I wouldn't show that code to *anyone*!! What if some newbie student saw this, and turned it in. (S)He would get an 'F'! You should have sprinkled in a few smiley faces ( :-} ) and grins () to show you were not serious. catch (good_input & e){ int num_points = e.n_points; std::cout << "Enter first point:(syntax x y) : "; point p; std::cin >p; double result = mag_n(p,1, num_points) ; std::cout << "path length = " << result <<'\n'; std::cout << "Do another set of points? (y/n) : "; std::string str; std::cin >str; if ( str.substr(0,1) != "y"){ throw quit(); } } } } catch (quit & e){return e.f();}} LMAOROF! #include void Painfull(int ouch){ while(true){ for(;;){ std::cout<<" Ha Ha"; Painfull(++ouch);}} return; } int main(){ Painfull(42); //

 P: n/a BobR wrote: kwikius wrote in message <11*********************@h54g2000cwb.googlegroups. com>... BobR wrote: 'goto' gives some C++ programmers 'the bends'! :-} I see. Sincere Apologies for that. OK, now I got rid of the gotos. How about this version? I'm making cool use of exceptions to keep stuff moving in this version. Better now huh? First 'the bends', now 'the willies'!! Oh dear... sorry :-( Why a typedef? Simply rename 'vect' to 'point'. You trying to be cute? Ah, you're 'just pulling my leg'! No way man! **Gross misuse** of exceptions to control normal program flow. It's fun to experiment, but, I wouldn't show that code to *anyone*!! What if some newbie student saw this, and turned it in. (S)He would get an 'F'! You should have sprinkled in a few smiley faces ( :-} ) and grins () to show you were not serious. hmmm... back to the drawing board I guess :-( .....;-) regards Andy Little Nov 29 '06 #25

 P: n/a BobR wrote: > kwikius wrote in message <11*********************@h54g2000cwb.googlegroups. com>... BobR wrote: 'goto' gives some C++ programmers 'the bends'! :-} I see. Sincere Apologies for that. OK, now I got rid of the gotos. How about this version? I'm making cool use of exceptions to keep stuff moving in this version. Better now huh? First 'the bends', now 'the willies'!! That's what happens when you don't have a Eustace looking out for you. Brian Nov 29 '06 #26

 P: n/a Default User wrote in message <4t*************@mid.individual.net>... >BobR wrote: >kwikius wrote in message<11*********************@h54g2000cwb.googlegroups .com>... BobR wrote:'goto' gives some C++ programmers 'the bends'! :-} I see. Sincere Apologies for that. OK, now I got rid of the gotos. How about this version? I'm making cool use of exceptions to keep stuff moving in this version. Better now huh? First 'the bends', now 'the willies'!! That's what happens when you don't have a Eustace looking out for you.Brian DANG! I just checked Fry's, and they are out of them!! Uhhh..... what's a 'Eustace'? [ seems I knew that once, but with my half dead single-brain-cell...] [ ....hope it's nothing like a eunuch!! ] -- Bob R POVrookie Nov 30 '06 #27

 P: n/a Default User wrote: BobR wrote: kwikius wrote in message <11*********************@h54g2000cwb.googlegroups. com>... BobR wrote: > >'goto' gives some C++ programmers 'the bends'! :-} > I see. Sincere Apologies for that. OK, now I got rid of the gotos. How about this version? I'm making cool use of exceptions to keep stuff moving in this version. Better now huh? First 'the bends', now 'the willies'!! That's what happens when you don't have a Eustace looking out for you. Yeah... Eustace came by and punched me on the nose and told me to stop being a smartass! regards Andy Little Nov 30 '06 #28

 P: n/a BobR wrote: > Default User wrote in message <4t*************@mid.individual.net>... BobR wrote: First 'the bends', now 'the willies'!! That's what happens when you don't have a Eustace looking out for you. Brian DANG! I just checked Fry's, and they are out of them!! Uhhh..... what's a 'Eustace'? [ seems I knew that once, but with my half dead single-brain-cell...] [ ....hope it's nothing like a eunuch!! ] Brian Nov 30 '06 #29

### This discussion thread is closed

Replies have been disabled for this discussion.

### Similar topics

Browse more C / C++ Questions on Bytes 