Recently, I was assigned a program that needs to be able to do the quadratic equation. I use this code

X = ((B*B) - 4*(A*C));
   X1 = (sqrt(X));
   X2 = 0-X1;
   X3 = X1/(2*A);
   X4 = X2/(2*A);
 
   Y = (-B + X3);
   Z = (-B - X3);
   Y1 = (-B + X4);
   Z1 = (-B - X4);
 
 
   printf("\nResult from adding the + roots:\t\t\t%f", Y);
   printf("\nResult from minusing the + roots:\t\t%f", Z);
   if (X1 > 0){
    printf("\nResult from adding the - roots:\t\t\t%f",Y1);
    printf("\nResult from minusing the - roots:\t\t%f",Z1);}

I'm not sure if that's even close to being right, but From my PoV it looks alright but, I haven't taken this subject for that long.. If anyone could please correct anything that looks wrong.. >_<.. Whenever I get like.. negative values or imaginaries It woudl do somethign like 1.#J or 1.#INFOOO depending on how many variables I set it for..

These are my declarations.. i'm not sure if this helps, but i hope it does >_<...

#include <stdio.h>
#include <conio.h>
#include <math.h>
 
char back;
int choice;        
float A, B, C, X, X1, X2, X3, X4, Y, Y1, Z, Z1;

Recommended Answers

All 3 Replies

Posting a complete example is always preferred. Check whether or not the argument to sqrt will be a negative value to avoid issues.

Member Avatar for iamthwee

>Whenever I get like.. negative values or imaginaries It woudl do somethign like 1.#J or 1.#INFOOO

I think that's becos it can't handle imaginary numbers. If you want it to, you have to write conditions for it.

I think that's becos it can't handle imaginary numbers. If you want it to, you have to write conditions for it.

I second that suggestion.
sqrt(X) cannot handle negative numbers, so you'll first have to check to see if X is negative. If it is, change it to a positive, and keep track of the fact that the radical was negative (with, say, a flag variable). Then follow through with the rest of the quadratic equation and make sure to note the imaginary component.

-- David

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.