I'm learning basics of C and writing a simple first order equation solver. I want the input to be exactly ax+b=c or ax-b=c, where a, b, c are double type. I'm employing scanf() to read in user input and to check if it's of the correct form. However, if I enter a negative double, -4.6 say, as the "a" in the equation, scanf()
won't read the a,b,c correctly. I'm using %lf inside scanf()
. How do I read a negative double, then? Many thanks.
My code:
#include <stdio.h>
int main(void)
{
double a,b,c,x;
printf("Enter the expression:\n");
if (scanf("%lfx%lf=%lf", &a, &b, &c) == 3)
{
x = (c - b)/a;
printf("x=%.2f\n", x);
}
else if (scanf("%lfx+%lf=%lf", &a, &b, &c) == 3)
{
x = (c - b)/a;
printf("x=%.2f\n", x);
}
else
printf("Invalid expression\n");
return 0;
}