I have an assignment saying create an array containing 100 random double numbers between 0 and 250, sorted into order by a separate function and then output on the screen.
Below is the code. My problem is where I try employ the function sort () in the main (), there's an error saying:
'Cannot convert 'double' to 'double*' for argument '1' to 'void sort(...'
Any idea what's going wrong? I don't know why it's trying to convert at all, would be very grateful for any explanation!
The function is declared in such a way that it expects to be passed an array of doubles (line 5). When you call sort on line 33, however, you pass it just one double, the double that is at sample[t]. I believe here you intend to pass the entire array, sample (not sample[t]).
And why would you call sort 100 times in a for loop?
sort(sample[t], size);
Here you are passing a double at position t of the array sample (meaning that you aren't passing an array [or pointer] as the function expects and the error message is telling you). Try this instead: sort(sample, size); // pass the pointer to the array, not an element of the array
Also, the call to sort should not be in the loop. You might also want to display the array before (as well as after) sorting to see that something actually happens (and what that something is).
Yeah I see what I did now. Getting an output now, but only getting 21 values and they're not even sorted, I can't see where things are going wrong, can you see at all?
Corrected what you pointed out and tweaked a coupla other things, new code:
Right you are Danny Toledo, but what you say in their edit, I see the logic but when I change it to -2 it doesn't sort quite correctly. The same thing happens if I change 'j' to 'j-1', and 'j+1' to 'j' on lines 10-13. I've changed line 9 so it sorts descending rather than ascending, to the following:
for(int j = 0;j < size - 1; j++)
I end up with numbers down to 0, then 41. With the code as it is there it sorts correctly. Still only getting 21 results, should I not be getting 100? Or am I misunderstanding how arrays work?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
int main()
{
double sample[100];
int t;
int size;
size = 100;
for (t=0; t<100; ++t) {
sample[t] = (double) (rand()%250);}
sort(sample, size);
for (t=0; t<100; ++t) {
cout<< sample[t]<< "\n";}
return 0;
}