Luke Luke - 15 days ago 4x
C Question

How can I modify my quadratic formula program in C to only calculate the square root once in the entire program?

I'm fairly new to the site and I'm attempting a challenge to improve what I already have here for my quadratic equation program. It functions already the way that I need it to, but I seek to learn how to improve it to the best of my ability without utilizing things that my course hasn't covered quite yet.

My instructor claims that there are multiple ways to go about this without having any more than one line of code utilizing the sqrt function, and I've been stumped on this for a while. I cannot seem to find a way to execute this program without at bare minimum two lines of code having sqrt().

If anybody has any suggestions or would mind steering me in the right direction, that would be greatly appreciated!

// Quadratic formula program redone
// Filename: quadeq3.cpp

#include <stdio.h>
#include <math.h>

float a,b,c,r1,r2,root = 0,disc,disc2,denom,real;

// Get the values for a, b, c

printf("\nEnter value for a: ");
if (a == 0) break; // Break the loop if a == 0

printf("Enter value for b: ");

printf("Enter value for c: ");

denom = 2*a; // Calculate 2a
disc = (b*b)-(4*a*c); // Calculate the discriminant
real = -b / denom; // Calculate the real (left) root

disc2 = -disc; // Used for case 3 imaginary roots
if (disc >= 0) root = sqrt(disc); // If not imaginary, use disc
if (disc < 0) root = sqrt(disc2); // If imaginary, use disc2

printf("\na = %2.1f",a);
printf("\nb = %2.1f",b);
printf("\nc = %2.1f",c);

// Case 1: discriminant > 0, 2 real roots

if (disc > 0)
r1 = (-b-root)/denom;
r2 = (-b+root)/denom;
printf("\n\n2 Real Roots:\n");
printf("\n%2.1f, %2.1f\n",r1,r2);

// Case 2: discriminant == 0, 1 real root

if (disc == 0)
printf("\n\n1 Real Root:\n");

// Case 3: discriminant < 0, imaginary roots

r2 = root/denom;
printf("\n\nImaginary Roots:\n");
printf("\n%2.1f + %4.3fi,%2.1f - %4.3fi\n",real,r2,real,r2);

// End the program

printf("\nNot a quadratic formula, program terminated!\n");

jxh jxh

If you want to keep to your current code structure:

if (disc < 0) disc2 = -disc;
else disc2 = disc;
root = sqrt(disc2);