Write a program that calculates the solutions of a second degree equation \(ax^2+bx+c=0\). Display 

  • INFINITE for infinite solutions
  • NO SOLUTION for no solutions
  • ottherwise, dislpay single, double or 2 solutions on one line (all numbers rounded to 2 decimals after the comma)

followed by a new line.

 


Difficulty level
This exercise is mostly suitable for students
#include<stdio.h>
#include <math.h>
 
int  main()
{
	int A, B, C;
 	float D; /* Discriminant */
 	scanf("%i %i %i", &A, &B, &C);

 	/* Calculus of the discriminant b^2-4ac */
 	D = B*B - 4.0*A*C;
 
 	if (A==0 && B==0 && C==0) /* 0x = 0 */
 		printf("INFINITE\n");
 	else if (A==0 && B==0)  /* Contradiction: c # 0 and c = 0 */  
 		printf("NO SOLUTION\n");
 	else if (A==0) /* bx + c = 0 */ 
    	{
     		printf("%.2f\n", (float)C/B);
    	}
 	else if (D<0)  /* b^2-4ac < 0 */ 
    	{ 
     		printf("%.2f+i%.2f ",  -B/2.0*A ,sqrt(-D)/(2.0*A) );
     	    printf("%.2f+i%.2f ",  -B/2.0*A ,-sqrt(-D)/(2.0*A) );
    	}
 	else if (D==0) /* b^2-4ac = 0 */ 
    	{
     		printf("%.2f\n", (float)-B/(2*A));
    	}
 	else /* b^2-4ac > 0 */ 
    	{ 
     		printf("%.2f ", (-B+sqrt(D))/(2*A));
     		printf("%.2f\n", (-B-sqrt(D))/(2*A));
    	}

	return 0;
}

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Rearranging values in an array