0

I need help with rand();. This program produces random number without repeating.
In my error list there are no errors.

Unhandled exception at 0x00414742 c++.exe: 0xC0000094: Integer division by zero.

int *numbers,range;


void randomize(unsigned numberToSelect){


for(unsigned i = 0; i < numberToSelect; i++){
   const int selectedElement = rand()%(range - i);
   const int temp = numbers[selectedElement];
   numbers[selectedElement] = numbers[range - i - 1];
   numbers[range - i - 1] = temp;
}


}
3
Contributors
5
Replies
6
Views
6 Years
Discussion Span
Last Post by Fbody
0

He did. What happens when (range == i)?

How does your code recognize and address that situation? It doesn't, but it needs to.

Edited by Fbody: n/a

0

I found another problem.
Unhandled exception at 0x00401022 in Reading a file.exe: 0xC0000005: Access violation reading location 0x00000024.

int *numbers;


void randomize(unsigned numberToSelect,unsigned range){


for(unsigned i = 0; i < numberToSelect; i++){

	const int selectedElement = rand()%(range - i);
	const int temp = numbers[selectedElement];
	numbers[selectedElement] = numbers[range - i - 1];//error
	numbers[range - i - 1] = temp;
}

}
0

That's because you still have the same basic problem.

As mentioned before, you need to find a way to GUARANTEE that the value of the caluculation (range - i) is NEVER less-than-or-equal-to zero (0). If it's zero or less when you hit that line, you are attempting to access array elements that have negative indexes. Such indexes neither exist nor are legal to access.

Edited by Fbody: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.