help me
hi,i write this program to sort 7 numbers,tell me my mistake.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
#include <iostream>
using namespace std;
void milad(double * a,double * b)
{
if (a<b)
{
double * c;
*c=*a;
* a=* b;
* b=* c;
}
}
int main()
{
int i,j;
double a[7];
for(i=0;i<7;i++)
{cin>>a[i];}
for(i=0;i<7;i++)
{
for(j=i;j<7;j++)
milad(&a[i],&a[j]);
}
for(i=0;i<7;i++)
{
cout<<a[i];
}
return 0;
}
|
one thing that immediately sticks out (but there's more stuff wrong I reckon) is
you are comparing the pointers, not the values that they hold.
ok,i fix this error but this program have runtime error,why?
line 19 makes no sense.
what are you trying to achieve? It looks like you are trying to do a strange mix of populating your array and getting user input.
you also don't initialise your 'c' pointer inside your milad() function.
Last edited on
In fact, why does c need to be a pointer at all?
in fact, why any pointers at all?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
|
int main()
{
double a[7];
// some test data
a[0] = 4;
a[1] = 2;
a[2] = 11;
a[3] = 65;
a[4] = 12;
a[5] = 76;
a[6] = 1;
bool bSwapped(true);
double temp(-1);
for(int i = 1; (i <= 7) && bSwapped; i++)
{
bSwapped = false;
for (int j=0; j < (7 -1); j++)
{
if (a[j+1] < a[j])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
bSwapped = true;
}
}
}
// display array elements here.
return 0;
}
|
Seriously, why use double instead of int?
Seriously, why use double instead of int? |
Erm... presumably because the OP wanted to sort floating-point numbers, rather than integers?
I fail to see how it makes any difference to solving the problem. The solution would be no different for ints.
Topic archived. No new replies allowed.