I'm a student listening to c programming lesson, and I'm using c++ to 'call-by-reference'. I don't know how to use c++ exactly, so I use c and save it into .cpp file. Anyway, I used a function to sort an array, and I now have an error. What should I do to solve this error?
#include <stdio.h>
#include <math.h>
double round(double value);
void sort(double a[],int cnt);
void swap(double& x,double& y);
int main()
{
int i;
double array[3];
for(i=0;i<3;i++){
scanf("%lf",&array[i]);
}
sort(array[3],3);
printf("%d %d %d",ceil(array[0]),floor(array[2]),round(array[1]));
return 0;
}
double round(double value)
{
return floor(value+0.5);
}
void sort(double a[],int cnt)
{
int i,j;
for(i=0;i<cnt-1;i++){
for(j=i+1;j<cnt;j++){
if(a[i]<a[j]){
swap(a[i],a[j]);
}
}
}
}
void swap(double& x,double& y)
{
int imsi=x;
x=y;
y=imsi;
}
Your sort(double a[], int cnt)
function takes as first argument double a[]
, which is syntactic sugar for a pointer double*
to the first element of an array. However in main()
you invoke it as
sort(array[3], 3); // you pass a double here, not a double*
In the call above you pass the 4-th element of the array array
, ie a double
, not a pointer double*
. To pass a pointer to the first element of the array, replace the above call with
sort(array, 3); // you now pass a double* (i.e. pointer to first element of the array)
The compiler is basically tell you what's wrong:
error: cannot convert 'double' to 'double*' for argument '1' to 'void sort(double*, int)' sort(array[3],3);
It expects a double*
but you pass a double
. It attempts to convert double
to double*
, but such conversion is impossible, hence the error.
In addition to your main concern (already answered by another user), you should probably change your swap()
function so that you aren't using an int
to store a double
. This could result in unexpected behavior.
Next problem which you'll facing with:
printf("%d %d %d",ceil(array[0]),floor(array[2]),round(array[1]));
for print float you may use "%f"
.
Simply to use cin
and cout
from library iostream
instead of scanf
and printf
for(i=0;i<3;i++) {
std::cin>>array[i]>>' ';
}
for(i=0;i<3;i++) {
std::cout>>array[i]>>' ';
}
btw http://www.cplusplus.com/reference/ could be useful for you on many reasons.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.