I'm a little new to programming, I'm trying to write a program to solve quadratic equation, here's my code:
#include <stdio.h>
#include <math.h>
void main (){
int a, b, c, delta;
float root1, root2;
delta = ( b * b ) - ( 4 * a * c );
printf("enter a, b, c, in such syntax ax^2 + bx + c:\n");
scanf("%d%d%d", &a, &b, &c);
printf("You mean %dx^2 + %dx + %d, delta=%f\n\n", a, b, c, delta);
if ( delta < 0 )
printf("The equation has no roots.\n");
if ( delta == 0 ){
root1 = -b / (2*a);
printf("The equaion has one root: %d\n", root1);
}
if ( delta > 0 ){
root1 = (-b + sqrt(delta)) / (2*a);
root2 = (-b - sqrt(delta)) / (2*a);
printf("root 1 = %f\nroot 2 = %f\n", root1, root2);
}
}
It's compiled without error, the problem is each time I run it, with same input, I get different answers!
$ ./qe
enter a, b, c, in such syntax ax^2 + bx + c:
2
4
2
You mean 2x^2 + 4x + 8, delta=0.000000
The equation has no roots.
$ ./qe
enter a, b, c, in such syntax ax^2 + bx + c:
2
4
2
You mean 2x^2 + 4x + 8, delta=0.000000
root 1 = 6543.122070
root 2 = -6545.122070
$ ./qe
enter a, b, c, in such syntax ax^2 + bx + c:
2
4
2
You mean 2x^2 + 4x + 8, delta=0.000000
root 1 = 8342.037109
root 2 = -8344.037109
$ ./qe
enter a, b, c, in such syntax ax^2 + bx + c:
2
4
2
You mean 2x^2 + 4x + 8, delta=0.000000
The equation has no roots.
.
.
I'm so confused. Whats the problem? My gcc version: 6.3.1 20170306 (GCC)
how should I fix this?
Thanx.
TL;DR Your code causes undefined behavior.
To elaborate, in the case
delta = ( b * b ) - ( 4 * a * c );
a, b, c are used uninitialized. They
can have trap representation
do not have their address taken.
So, this invoke UB.
You need to
first check for the success of scanf() call
move the calculation of delta after the successful scanning for values for the involved operands.
Also, to add, for a hosted environment, the conforming signature for main() would be int main(void), not void main ()
Related
#include <math.h>
#include <stdio.h>
main() {
int a, b, c, x, x1, x2;
printf("enter the values of a,b,c:");
scanf("%d%d%d", &a, &b, &c);
printf("The quadratic equation is %d*pow(x,2)+%d*x+%d=0", a, b, c);
if (pow(b, 2) - 4 * a * c >= 0) {
x1 = (-b + sqrt(pow(b, 2) - 4 * a * c)) / 2 * a;
x2 = (-b - sqrt(pow(b, 2) - 4 * a * c)) / 2 * a;
printf("the roots of the equation are x1=%d,x2=%d", x1, x2);
}
else
printf("roots of the equation in the form of x+iy and x-iy");
return 0;
}
Is this code alright for the given question, i had a bit confusion at that printing imaginary roots. could you please help
Use proper main prototype.
Use floating point numbers instead of integers
pow(b,2) == b*b
/ 2 * a -> / (2 * a)
int main(void) {
double a, b, c, x, x1, x2;
printf("enter the values of a,b,c:");
if(scanf("%lf %lf %lf", &a, &b, &c) != 3) { /* handle error */}
printf("\nThe quadratic equation is %f*x^2+%f*x+%f=0\n", a, b, c);
if (b*b - 4 * a * c >= 0) {
x1 = (-b + sqrt(b*b - 4 * a * c)) / (2 * a);
x2 = (-b - sqrt(b*b - 4 * a * c)) / (2 * a);
printf("the roots of the equation are x1=%f,x2=%f\n", x1, x2);
}
else
{
double r = -b / (2*a);
double z = sqrt(fabs(b*b - 4 * a * c));
printf("the roots of the equation are x1 = %f + i%f, x2 = %f - i%f", r,z,r,z);
}
}
https://gcc.godbolt.org/z/Ys1s8bWY7
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.
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
I see some problems with the code. First, I suggest you to use double instead of float. They offer much better precision and an ideal calculator needs precision. Secondly, you do:
Z = pow(CheckF, 1/2);
You should use sqrt(CheckF) since there is a dedicated function in C for square roots! The following works for me so if you fix the above two problems, your code will probably work.
int main() {
double 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: ");
A = 3;
B = 32;
C = 2;
double CheckF = (B * B - 4 * A * C);
if (CheckF >= 0) {
Z = sqrt(CheckF);
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);
} else if (A1 != A2) {
printf("Roots of equation are %f and %f \n", A1, A2);
}
}
}
I run it in my code::blocks to show 3 angles of triangle where 3 sides are given by the user. But if I run and give 3 sides such as 3,4,5 output will be -1.#J -1.#J -1.#J. What's wrong with my code?
#include <stdio.h>
#include <math.h>
int main()
{
float a, b, c, A, B, C, R, s, pi, area;
pi = acos(-1);
scanf("%f %f %f", &a, &b, &c);
s = (a+b+c)/2;
area = sqrt(s*(s-a)*(s-b)*(s-c));
R = (a*b*c)/(4*area);
A = (180/pi)*asin(a/2*R);
B = (180/pi)*asin(b/2*R);
C = (180/pi)*asin(c/2*R);
printf("%.2f %.2f %.2f", A, B, C);
return 0;
}
You need more parentheses. You have:
A = (180/pi)*asin(a/2*R);
You need:
A = (180/pi)*asin(a/(2*R));
What you wrote is equivalent to:
A = (180 / pi) * asin((R * a) / 2);
You should also check your inputs so that a 'triangle' with sides 1, 1, 3 is rejected, for example. Negative and zero lengths should probably be rejected too.
Revised code
#include <stdio.h>
#include <math.h>
int main(void)
{
float a, b, c, A, B, C, R, s, pi, area;
pi = acos(-1);
if (scanf("%f %f %f", &a, &b, &c) != 3)
{
fprintf(stderr, "Failed to read 3 numbers\n");
return 1;
}
if (a <= 0 || b <= 0 || c <= 0)
{
fprintf(stderr, "Sides must be strictly positive\n");
return 1;
}
s = (a + b + c) / 2;
if (a > s || b > s || c > s)
{
fprintf(stderr, "The three sides %.2f, %.2f, %.2f do not form a triangle\n",
a, b, c);
return 1;
}
area = sqrt(s * (s - a) * (s - b) * (s - c));
R = (a * b * c) / (4 * area);
A = (180 / pi) * asin(a / (2 * R));
B = (180 / pi) * asin(b / (2 * R));
C = (180 / pi) * asin(c / (2 * R));
printf("Sides: %6.2f %6.2f %6.2f\n", a, b, c);
printf("Angles: %6.2f %6.2f %6.2f\n", A, B, C);
return 0;
}
Note that error messages are reported on standard error. All lines of output end with a newline in the format. The input data is echoed. All of these are good practices.
Example runs
$ triangle <<< "0 1 3"
Sides must be strictly positive
$ triangle <<< "-1 1 3"
Sides must be strictly positive
$ triangle <<< "1 1 3"
The three sides 1.00, 1.00, 3.00 do not form a triangle
$ triangle <<< "3 4 5"
Sides: 3.00 4.00 5.00
Angles: 36.87 53.13 90.00
$ triangle <<< "3 3 3"
Sides: 3.00 3.00 3.00
Angles: 60.00 60.00 60.00
$ triangle <<< "1 1.4141 1"
Sides: 1.00 1.41 1.00
Angles: 45.00 nan 45.00
$ triangle <<< "1 1 1.4141"
Sides: 1.00 1.00 1.41
Angles: 45.00 45.00 nan
$ triangle <<< "1 1 1.414"
Sides: 1.00 1.00 1.41
Angles: 45.01 45.01 89.98
$ triangle <<< "1 1 1.41421356237309504880"
Sides: 1.00 1.00 1.41
Angles: 45.00 45.00 nan
$
I'm a little puzzled about the nan values. However, changing the data type from float to double and adjusting the scanf() formats appropriately (%lf instead of %f) seems to 'resolve' (maybe 'evade' is a better word) that problem.
It should be
A = (180/pi)*asin(a/(2*R));
rather than
A = (180/pi)*asin(a/2*R);
Insufficient parentheses.
Additional detail:
asin(x) is only defined for values [-1.0 ... 1.0]. With select input, corrected code may get a a/(2*R) that is just a little bit greater than 1.0 due to calculation issues with floating point.
s = (a+b+c)/2;
// Jonathan Leffler tests
area = sqrt(s*(s-a)*(s-b)*(s-c));
R = (a*b*c)/(4*area);
// add test
double R2 = R*2.0;
A = (a>R2) ? 180/pi : (180/pi)*asin(a/R2);
...
I could not get your posted code to work, even given all the comments and prior answers.
However, this works very well.
Note: I did not include code to error check the call to scanf() to keep the presentation simple
#include <stdio.h>
#include <math.h>
#define RAD_2_DEG (57.2958)
#define TOTAL_DEG (180.0)
int main( void )
{
int a, b, c; // user entered lengths of sides of triangle
double A, B, C; // calculated angle values in degrees
scanf( "%d %d %d", &a, &b, &c );
// note: acos returns the angle in radians
// and one radian is (approx) 57.2958 degrees
A = RAD_2_DEG * acos((double)(b*b + c*c - a*a)/(2.0*b*c));
B = RAD_2_DEG * acos((double)(c*c + a*a - b*b)/(2.0*a*c));
// third angle done this way to absorb fractional degree errors
C = TOTAL_DEG -(A + B);
printf("%.2f %.2f %.2f", A, B, C);
return 0;
}
Whenever I try running this, it returns the wrong solution, for example:
A: 303
B: 405
C: 50
Real solution: −0.13762776465722773
My solution : -110079.531250
#include <stdio.h>
#include <math.h>
int main(){
float a;
float b;
float c;
float solution;
float d;
printf("A: ");
scanf("%f", &a);
printf("B: ");
scanf("%f", &b);
printf("C: ");
scanf("%f",&c);
d = b * b - 4 * a * c;
solution = (-b - sqrt(d))/ 2*a;
printf("%f", solution);
}
You forgot BODMAS. Replace (-b - sqrt(d))/ 2*a by (-b - sqrt(d))/ (2*a)
solution = (-b - sqrt(d))/ (2*a);
Two things.
You need to watch out for the order of operations.
solution = (-b - sqrt(d)) / (2*a);
And depending on your customer you need to consider the accuracy of your result.
See "Avoiding loss of significance" for more information
And finally - i had a bit of fun writing my own version of your program:
#include <stdio.h>
#include <math.h>
void printLineSolution( double a, double b, double c );
int main()
{
printLineSolution(303,405,50);
printLineSolution(1,2,0);
printLineSolution(1,2,-1);
printLineSolution(1,-2,-3);
printLineSolution(1,-6,9);
printLineSolution(1,3,3);
getchar();
}
void printLineSolution( double a, double b, double c )
{
double d = (b * b) - (4 * a * c);
printf("(%lg)x^2 + (%lg)x + (%lg) = 0 ", a, b, c);
if( a == 0 )
{
printf("=> not quadratic");
}
else
{
if( 0 > d )
{
double r = - b / (2*a);
double i = sqrt( -d ) / (2*a);
printf("=> 2 complex: %lg + %lgi ; %lg - %lgi", r, i, r, i);
}
else if ( 0 == d )
{
double solution = - b / (2*a);
printf("=> 1 real: %lg", solution);
}
else
{
double s1 = (- b + sqrt( d ) ) / (2*a);
double s2 = (- b - sqrt( d ) ) / (2*a);
printf("=> 2 real: %lg ; %lg", s1, s2);
}
}
printf("\n");
}
I've been trying to look up on Google how to put in an equation in my program but wasn't able to find any. How do you include:
x = ( -b + √b2 - 4ac ) / 2a
in the program?
Here's my code:
{
int a, b, c;
float x;
//statements
printf("Enter three integers: ");
scanf("%d %d %d", &a, &b, &c);
//computeforX
x = ( -b + √b2 - 4ac ) / 2a
printf("The value of x is %.1f", x);
return 0;
}
Assuming we're talking about C (or C++) here, you will need to investigate the sqrt function, and maybe also the pow function as well (although that's unnecessary because b-squared can be computed as b*b).
Note that you will need to convert all of your input values to float or double before you start the calculation, otherwise you will not get the intended result.
You need a table to allow you to translate:
a+b -> a+b
a-b -> a-b
a/b -> a/b
ab -> a*b
√x -> sqrt(x)
x² -> x*x (If you want to square something more complicated it might be best to use a temporary variable for the value to be squared, breaking your equation up into pieces.)
Note that if you divide an int by an int in C you get an int. So better convert those ints to doubles before dividing.
If we are dealing with C++ it would be something like
#include <iostream.h>
#include <cmath>
int main ()
{
//Declare Variables
double x,x1,x2,a,b,c;
cout << "Input values of a, b, and c." ;
cin >>a >>b >>c;
if ((b * b - 4 * a * c) > 0)
cout << "x1 = (-b + sqrt(b * b - 4 * a * c)) / (2 * a)" &&
cout << "x2 = (-b + sqrt(b * b - 4 * a * c)) / (2 * a)";
if else ((b * b - 4 * a * c) = 0)
cout << "x = ((-b + sqrt(b * b - 4 * a * c)) / (2 * a)"
if else ((b * b - 4 * a * c) < 0)
cout << "x1 = ((-b + sqrt(b * b - 4 * a * c) * sqrt (-1)) / (2 * a) &&
cout << "x2 = ((-b + sqrt(b * b - 4 * a * c) * sqrt (-1)) / (2 * a);
return (0);
}
Now why do i have this wierd feeling I just did someone's first semester programming class' homework?
Granted its been years and I don't even know if that will compile but you should get the idea.
I am really depressed looking the quality of above answers and help, which has been given.
I hope to improve the content of this thread.
One can compile the C file below with the command line gcc file.c -o file -lm.
Herewith a possible solution in C:
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
int main(){
int da, db, dc;
double x, a,b,c;
//statements
printf("Enter three integers: ");
scanf("%d %d %d", &da, &db, &dc);
a = (double)da;
b = (double)db;
c = (double)dc;
//computeforX
x = (double) ( -b + sqrt(b * b) - 4 * a * c ) / ( 2 * a ) ;
printf("The value of x is %g \n", x);
return 0;
}