Write a program to determine the roots of a quadratic equation.
Quadratic Equation: a*x^2+b*x+c=0
Example:
Input: a = 1, b = -5, c = 6 Output: Roots are: 3.000000, 2.000000
Approach
C
#include <stdio.h>#include <math.h>int main(){int a, b, c;printf("Enter coefficients of quadratic equation :");scanf("%d%d%d", &a, &b, &c);if (b * b - 4 * a * c < 0){printf("Roots are imaginary ");}else{float root1 = (float)(-b + sqrt(b * b - 4 * a * c)) / 2 * a;float root2 = (float)(-b - sqrt(b * b - 4 * a * c)) / 2 * a;printf("Roots are: %f, %f ", root1, root2);}return 0;}
Java
import java.util.Scanner;public class RootsQuadraticEquation {public static void main(String[] args) {System.out.println("Enter coefficients of quadratic equation :");Scanner sc = new Scanner(System.in);int a = sc.nextInt();int b = sc.nextInt();int c = sc.nextInt();if (b * b - 4 * a * c < 0) {System.out.println("Roots are imaginary ");} else {float root1 = (float) (-b + Math.sqrt(b * b - 4 * a * c)) / 2 * a;float root2 = (float) (-b - Math.sqrt(b * b - 4 * a * c)) / 2 * a;System.out.printf("Roots are: %f, %f ", root1, root2);}sc.close();}}
No comments:
Post a Comment