Thanks for your replies guys. I've tried using the scanf("%f %f %f", &a, &b, &c) != 3 idea and it does seem to determine when a letter is entered instead of a number and prints :"You have entered an illegal character".
However as someone suggested, the invalid input is still in the input buffer and causes the following if statement to be true and run as well which is undesirable:
Code:
if (determinate<0)
printf("There are no real roots to this quadratic equation.\n");
I tried to stop the if statement running by changing it to run if the determinate is <0 and if the number of successfully entered numbers is 3 as you can see below, but the if statement still runs.
Code:
if (determinate<0 && scanf("%f %f %f", &a, &b, &c) == 3);
{printf("There are no real roots to this quadratic equation. \n");}
Any ideas?
The full code is below.
Code:
#include <stdio.h>
#include <math.h>
main()
{
float a, b, c, discriminant, root1, root2;
printf("Enter the required a followed by b followed by c and the program will calculate the roots for you: \n");
scanf("%f %f %f", &a, &b, &c);
printf("\n");
discriminant = (b*b)-(4.0*a*c);
if (scanf("%f %f %f", &a, &b, &c) != 3)
{printf("You have entered an illegal character.");}
if (discriminant>0)
{root1 = (((-b)+sqrt(determinate))/(2*a));
root2 = (((-b)-sqrt(determinate))/(2*a));
printf("Root 1 = %8.5f Root 2 = %8.5f\n", root1, root2);}
if (discriminant == 0)
{root1 = (((-b)+sqrt(determinate))/(2*a));
printf("Repeated root = %8.5f \n", root1);}
if (discriminant<0 && scanf("%f %f %f", &a, &b, &c) == 3);
{printf("There are no real roots to this quadratic equation. \n");}
system ("pause");}
BTW determinate is the same as discriminant, I was taught to use determinate at school.
Thank you
Paul