Search code examples
ccalculatorquadratic

Roots of equation in C


I am relatively new to C, and am trying to improve myself in it. I made a calculator and added the quadratic equation solver to it, cause i know the formula of finding the roots. But i am faced with two problems.

Code:

#include <stdio.h>
#include <maths.h>
#include <stdlib.h>
#include <windows.h>

main(){
        float A1, A2, A, B, C, ans, Z;
        printf("Welcome to Quadratic Equation solver. Enter the coefficient of X^2, followed by\nthe coefficient of X, followed by the integer value.\n\nEnter values: ");
        scanf("%f%f%f", &A, &B, &C);
        CheckF = (B * B - 4 * A * C);
        if (CheckF < 0) {
          system("COLOR B4");
          printf("This calculator HeX, currently cannot handle complex numbers.\nPlease pardon my developer. I will now redirect you to the main menu.\n");
          system("pause");
          system("cls");
          system("COLOR F1");
          goto Start;
        } else if (CheckF >= 0) {
            Z  = pow(CheckF, 1/2);
            A1 = (-B + Z)/(A+A);
            A2 = (-B - Z)/(A+A);
          if (A1 == A2) {
            ans = A1;
            printf("\nRoot of equation is %f (Repeated root)\n", ans);
            Sleep(250);
          } else if (A1 != A2) {
            printf("Roots of equation are %f and %f \n", A1, A2);
            Sleep(250);
          }
        }
      }

Problem 1: When i run the code and input 3 32 2, mathematically the output should be Roots of equation are -0.06287 and -10.6038, that i double checked with my sharp calculator. However, the output that i got was was off: Roots of equation are -5.166667 and -5.500000 i am totally unsure why is it not computing the correct roots of the equation.

Problem 2: Some roots do not have the coefficient of X^2, for example (2X + 2), which can be solved to get repeated roots of -2, (6X - 3), which gives us that x is 0.5 repeated. However, according to the quadratic equation, which is divided by 2A, will never work, as it is divided by 0. What is the possible way out of this situation? Is it to check if A = 0 then do something else? Any help will be appreciable.


Solution

  • integer division

    pow(CheckF, 1/2) is 1.0 as 1/2 is integer division with a quotient of 0.

    // Z  = pow(CheckF, 1/2);
    Z  = pow(CheckF, 1.0/2.0);
    // or better
    Z  = sqrt(CheckF);
    // Even better when working with `float`.
    // Use `float sqrtf(float)` instead of `double sqrt(double)`.
    Z  = sqrtf(CheckF);
    

    Best - re-write using double instead of float. Scant reason for using float here. double is the C goto floating point type.

    Other issue

    //#include <maths.h>
    #include <math.h>
    
    // main() {
    int main(void) {
    
    // CheckF = (B * B - 4 * A * C);
    float CheckF = (B * B - 4 * A * C);
    
    // goto Start;
    

    Use an auto formater