Thread: More Array code problems

  1. #1
    Registered User
    Join Date
    Dec 2003
    Posts
    6

    More Array code problems

    In this program I'm trying to use arrays to keep track of the (x,y,z) coordinates of a given number of projectiles, starting from (0,0,0). I hope to use this as the basis for a collision system for a game. The only clear error is the x value has an incorrect value after the program executes. I think there is also problems with the looping, but I can probably fix that myself. Here's the code.

    Code:
    Code:
    #include <iostream>
    
    using std::cout;
    using std::cin;
    using std::endl;
    
    
    int a,n,x;
    int forcex, forcey, forcez;
    
    int main()
    {
    	
    	cout<<"How many projectiles are fired?:";
    	cin>>a;
    	cout<<"What is the vector acceleration?"<<endl;
    	cout<<"x:";
    	cin>>forcex;
    	cout<<"y:";
    	cin>>forcey;
    	cout<<"z:";
    	cin>>forcez;
    	cout<<"There is force at ("<<forcex<<","<<forcey<<","<<forcez<<")"<<endl<<endl;
    
    	int posx[]={0}, posy[]={0}, posz[]={0};
    	
    	for(n=0;n<a;n++)
    	{
    		posx[n] = posx[n]+forcex;
    		posy[n] = posy[n]+forcey;
    		posz[n] = posz[n]+forcez;
    	
    		for(x=1;x<n+2;x++)
    		{			
    			cout<<"The position of particle "<< n+1 <<" is:"<<endl;
    			cout<<"("<<posx[x]<<","<<posy[x]<<","<<posz[x]<<")"<<endl<<endl;
    		}
    	}
    
    	return 0;
    }
    When inputting all variables as 1, the output coordinate is: (1245120,1,1). Assuming that I'm not changing the values of the posx[] array, I dont know what is causing this error. Please help!

  2. #2
    Registered User
    Join Date
    Aug 2003
    Posts
    470
    It looks like you want something like

    int posx[MAX_PROJECTILES] = { 0 };
    int posy[MAX_PROJECTILES] = { 0 };
    int posz[MAX_PROJECTILES] = { 0 };
    Instead of the array with only one element.

    I'm also not sure what you're inner loop with indice x also needs to be fixed. Also you don't ever want variables for indices global, because it makes your program hard to understand.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem(s) with an array!!
    By Leojeen in forum C Programming
    Replies: 6
    Last Post: 05-02-2008, 07:26 PM
  2. problems finding the average of an array column
    By mrgeoff in forum C Programming
    Replies: 4
    Last Post: 04-18-2005, 11:49 PM
  3. Code: An auto expanding array (or how to use gets() safely).
    By anonytmouse in forum Windows Programming
    Replies: 0
    Last Post: 08-10-2004, 12:13 AM
  4. Interface Question
    By smog890 in forum C Programming
    Replies: 11
    Last Post: 06-03-2002, 05:06 PM
  5. array problems
    By slamit93 in forum C++ Programming
    Replies: 7
    Last Post: 04-25-2002, 01:09 PM