c - Solve quadratic; learning functions; program doesn't return values -
please, take @ program wrote part of assignment after chapter 7 programming in c. program should return roots of quadratic based on values of constants typed in user. program should simple; @ beginner's level. although compiler compile program, output prompting message. after enter 3 values, nothing happens, program ends, , @ terminal. have edited program. , if enter values make discriminant less 0,
please, enter 3 constants of quadratic: 1 2 3 roots imaginary square roots of quadratic are:
thus main function statement still appears.
if enter other values,
please, enter 3 constants of quadratic: 1 8 2 -0.256970 , -7.743030square roots of quadratic are:
do see formatting? why happen?
#include <stdio.h> #include <math.h> float abs_value (float x); float approx_sqrt (float x); float solve_quadratic (float a, float b, float c); // main function prompts user 3 constant values fill quadratic // ax^2 + bx + c int main(void) { float a, b, c; printf("please, enter 3 constants of quadratic: \n"); if (scanf ("%f %f %f", &a, &b, &c) == 3) printf("square roots of quadratic are: \n", solve_quadratic(a,b,c)); return 0; } // function take absolute value of x used further in square root function float abs_value (float x) { if (x < 0) x = - x; return x; } // function compute approximate square root - newton raphson method float approx_sqrt (float x) { float guess = 1; while (abs_value (pow(guess,2) / x) > 1.001 || abs_value (pow(guess,2) / x) < 0.999) guess = (x / guess + guess) / 2.0; return guess; } // function find roots of quadratic float solve_quadratic (float a, float b, float c) { float x1, x2; float discriminant = pow(b,2) - 4 * * c; if (discriminant < 0) { printf("roots imaginary\n"); return -1; } else { x1 = (-b + approx_sqrt(discriminant)) / (2 * a); x2 = (-b - approx_sqrt(discriminant)) / (2 * a); } return x1, x2; }
thank you!
if (scanf ("%f %f %f", &a, &b, &c) == 1)
scanf
returns number of arguments succesfully scanned. in case, want 3, not 1.
Comments
Post a Comment