Thursday, July 30, 2009

C++ help with multiple inputs?

I'm making a program for class that needs to ask





1) How many points on a graph there are.





int n;


cout%26lt;%26lt;"enter number of points on graph";


cin%26gt;%26gt;n;





2)Ask for the x and y values for each point based on the number of points.





Output would be:





Enter X_1:


Enter Y_1:


Enter X_2:


Enter Y_2:


Enter X_n:


Enter Y_n:





How would I go about getting this set up. I'm guessing something like:





for(int k=1; k%26lt;=n; k++)


{


cout%26lt;%26lt;"Enter the value of x_"%26lt;%26lt;k%26lt;%26lt;endl;


cin%26gt;%26gt; ; %26lt;--- What goes here?


cout%26lt;%26lt;"Enter the value of y_"%26lt;%26lt;k%26lt;%26lt;endl;


cin%26gt;%26gt; " %26lt;---What goes here?


}





Thats probably wrong, but I just don't know how to start it out to do it right and to have each number maintain the input value.

C++ help with multiple inputs?
First of all, ask yourself what datatype is each point? It's a floating point value, so we'll use a double to store the points. Second, ask yourself how are you storing the points? It's a giant list of cartesian points, so there's a few ways to deal with that. A simple way right now is using a vector to store a sequence of doubles.





Include:


#include %26lt;vector%26gt;





Declare:


vector%26lt;double%26gt; cartPoints;





Now you need to take in with cin a double and store it in the vector.


So you need a temporary storage variable:


double temp;





just do cin %26gt;%26gt; temp to get the double.


Then do cartPoints.push_back(temp) to store it in the vector.
Reply:You didn't have it TOTALLY wrong, you actually did a very good start and had the right concept, you just need to learn to use arrays in cases like this, here is a moded version of your code





int array1[x];


int array2[y];


//if you have not gotten to understand dynamic arrays


//yet then simple use the HIGHEST possible value for your array,





for(int k=1; k%26lt;=n; k++)


{


cout%26lt;%26lt;"Enter the value of x_"%26lt;%26lt;k%26lt;%26lt;endl;


cin%26gt;%26gt; array[x]; %26lt;--- What goes here?


cout%26lt;%26lt;"Enter the value of y_"%26lt;%26lt;k%26lt;%26lt;endl;


cin%26gt;%26gt; array2[y]; " %26lt;---What goes here?


}





I'm not really sure how your doing your project, but since you posted just a for loop, i would assume you needed 2 arrays and not just one two dimensional array.


No comments:

Post a Comment