Why does &x1 cannot be accpeted
int calculte (float a, float b, float c, float &x1, float &x2)
I'm trying to solve quadratic equation, here's my full program
#include<stdio.h>
#include<math.h>
int calculte (float a, float b, float c, float &x1, float &x2){
float delta = b*b -4*a*c;
if (delta <0) {
x1 =x2 = 0.0;
return 0;
} if (delta == 0) {
x1 = x2 = -b/(2*a);
return 1;
} if (delta >0) {
delta = sqrt(delta);
x1 = (-b-delta)/(2*a);
x2 = (-b - delta)/(2*a);
return 2;
}
}
int main () {
float a, b, c, x1, x2;
do {
scanf ("%f %f %f", &a, &b, &c);
}
while (!a);
int ans = calculte (a,b,c,x1,x2);
if (ans==0) {
printf ("NO");
}
if (ans==1){
printf ("%.2f",x1);
}
if (ans==2) {
printf ("%.2f %.2f", x1, x2);
}
}
I am new to programming, so hope you guys can explain me more details.
You cannot use references in C.
Instead of that, you should make the arguments to pointers by changing &
to *
.
Also the function body and calling have to be changed according to that.
#include<stdio.h>
#include<math.h>
int calculte (float a, float b, float c, float *x1, float *x2){ /* change the arguments to pointers */
float delta = b*b -4*a*c;
if (delta <0) {
*x1 =*x2 = 0.0; /* dereference the pointers */
return 0;
} if (delta == 0) {
*x1 = *x2 = -b/(2*a); /* dereference the pointers */
return 1;
} if (delta >0) {
delta = sqrt(delta);
*x1 = (-b-delta)/(2*a); /* dereference the pointer */
*x2 = (-b - delta)/(2*a); /* dereference the pointer */
return 2;
}
}
int main () {
float a, b, c, x1, x2;
do {
scanf ("%f %f %f", &a, &b, &c);
}
while (!a);
int ans = calculte (a,b,c,&x1,&x2); /* add & to get the pointers */
if (ans==0) {
printf ("NO");
}
if (ans==1){
printf ("%.2f",x1);
}
if (ans==2) {
printf ("%.2f %.2f", x1, x2);
}
}