how to put in mathematical equation in C
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开发者_Python百科 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 int
s to double
s 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;
}
精彩评论