Search code examples
cfloating-pointscanf

Display double variable with scanf and without scanf


I have an issue about display the value of a variable with double date type.

I already had looked at here, text, text and here. However it did not help me.

Below is the issue: Here is the **code with scanf command. **

#include <stdio.h> 
int main(){
double a, b, c , x0, Delta; 
printf("Inter three numbers:");
scanf("%lf, %lf, %lf", &a, &b, &c);  
Delta = b*b - 4*a*c;  
printf("The value of Delta is %f \n", Delta);
x0 = -b/(2.0*a); 
printf("\n the value of x0= %f", x0); 
return 0; 
}

With scanf command I type 1 2 1, then $x0=0.000000$. It is the wrong result.

Without scanf command If I type $a=1,b=2,c=1$ directly, then I got x0 = 1.000000.

I want to use scanf command and obtain the correct result. It mean to obtain x0=1.000000 when a=1, b =2, c=1.


Solution

  • Your scanf format string has commas between the numbers, so that's how it's expecting the input to look.

    If you enter 1 2 1, the first %lf is matched by 1, but then 2 doesn't match the comma, so it stops reading at that point, leaving b and c uninitialized.

    You need to either enter the numbers with commas between them, or remove the commas from the format string.