Program to Compute real roots of a quadratic expression

roots of a quadratic expression

Problem Description

Program to find the real roots of a quadratic equation as given below
ax2 + bx + c
is a quadratic equation, we need to find the real root for these type of expressions, the formula to find the root is as given below
Where Discriminant of a Quadratic represented by D = b2 – 4ac, which reveals the type of roots as per the following conditions

  1. If D >0, the roots would be real
  2. If D = 0, then both roots would be equal
  3. If D < 0, the roots would be imaginary.

C Program

#include<stdio.h>
#include<math.h>
int main() {
int a,b,c;
float d,r1,r2;
printf("Enter 3 constant a,b,c: ");
scanf("%d%d%d",&a,&b,&c);
d = b * b - 4 * a * c;
if (d < 0) {
printf("Roots are imagenary");
}else {
r1 = (b + sqrt(d)) / (2 * a);
r2 = (b - sqrt(d)) / (2 * a);
printf("Root1 = %.2f\nRoot2 = %.2f",r1,r2);
}
return 0;
}

C++ program

#include<iostream>
#include<math.h>
using namespace std;
int main() {
int a,b,c;
cout << "Enter 3 constant a,b,c: ";
cin >> a >> b >> c;
float d = b * b - 4 * a * c;
if(d < 0 ) {
cout << "Roots are imagnary";
} else {
float r1 = (b + sqrt(d)) / (2 * a);
float r2 = (b - sqrt(d)) / (2 * a);
cout << "Root1 = " << r1 << endl;
cout << "Root2 = " << r2 << endl;
}
return 0;
}

Java

class RealRoots {
public static void main(String args[]) {
int a,b,c;
java.util.Scanner sc = new java.util.Scanner(System.in);
System.out.print("Enter value of a,b,c: ");
a = sc.nextInt();
b = sc.nextInt();
c = sc.nextInt();
int d = b * b - 4 * a * c;
if( d < 0 ) {
System.out.println("Roots are imagnary");
} else {
double r1 = (b + Math.sqrt(d)) / (2 * a);
double r2 = (b - Math.sqrt(d)) / (2 * a);
System.out.println("Root1 = "+r1);
System.out.println("Root2 = "+r2);
}
}
}

Go Lang


package main
import ("fmt";"math")
func main() {
var a,b,c float64
fmt.Print("Enter value of a,b,c: ")
fmt.Scan(&a,&b,&c)
d := b * b - 4 * a * c
if(d < 0) {
fmt.Println("Roots are imagnary")
}else {
r1 := (b + math.Sqrt(d)) / (2 * a)
r2 := (b - math.Sqrt(d)) / (2 * a)
fmt.Println("Root11 = ",r1)
fmt.Println("Root2 = ",r2)
}
}

PHP

<?php
if(isset($_POST['sub'])) {
$a = $_POST['a'];
$b = $_POST['b'];
$c = $_POST['c'];
$d = $b * $b - 4 * $a * $c;
if($d < 0) {
echo "Roots are imaginary";
} else {
$root1 = ($b + sqrt($d))/(2 * $a);
$root2 = ($b - sqrt($d))/(2 * $a);
echo "Root1 = ".$root1." Root2 = ".$root2;
}
}
?>

Comments

Popular posts from this blog

Program to calculate telephone bill

Arrays in C Language

String in golang

Sum of two numbers in go lang

Pointers in C Language

Decision Making Statements

Say Hello world in Go lang

Decision Making in Go lang

Program to convert time from seconds to hours, minutes and seconds

Installing go lang