Jump to content
  • Advertisement
Sign in to follow this  
ostamo1

is this correct

This topic is 5069 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

i need to create an integer array that holds 10 random values. Create a loop to find the average of those 10 values and print the result. i was wondering if my code was correct
#include <iostream>

main()
{
	int intarray[10]={0};
	int x = 0;
	int average = 0;
	for (x; x < 10; x++)
	{
		intarray[x] = rand();
		
		average += intarray[x];
		
	}
	std::cout << average/10  << std::endl;;
	return 0;
}


Share this post


Link to post
Share on other sites
Advertisement
Guest Anonymous Poster
Looks alright to me, why don't you try running it and see if it works? (Unless you know of some specific problem with it already...)

Share this post


Link to post
Share on other sites
int intarray[10]={0};

I don't think that's valid. Try:

int intarray[10];


Also, you have one too many semicolons on the second last line.

Share this post


Link to post
Share on other sites
it works i was just checking to see if i was doing it the right way and to make sure i understood the assignment thats all
thanks for the reply

int intarray[10]={0};
that line initializes the whole array to zero

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
You allways get the same number becouse you dont seed the random number generator. You should call srand() with a different value every time at the start of the program.

Share this post


Link to post
Share on other sites
Quote:
Original post by ostamo1
it works i was just checking to see if i was doing it the right way and to make sure i understood the assignment thats all
thanks for the reply

int intarray[10]={0};
that line initializes the whole array to zero


Actually it only sets intarray[0] to 0. YOur compiler in debug mode is likely zeroing the array, so it looks zeroed out to you. Try changing it to int intarray[10]={1}; and you will see what I mean. The correct way to zero it is with meset, a for loop or int array[0]={0,0,0,0,0,0,0,0,0,0}; .

// Only the first element will be one
#include <iostream>

int main()
{
int a[10]={1};
for (int i=0; i<10; ++i)
std::cout << "a["<<i<<"]="<< a<< std::endl;;
std::cin.ignore();
return 0;
}


Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!