Quadratic Equation in C - c

Here is a program that I'm trying to fix. I entered 1,5,6 and there should be 2 solutions and it said only 1 solution exists. I'm also trying to make it display decimal values(should I use double?). Below is my code, What am I doing wrong?
#include <stdio.h>
#include <math.h>
int main(void)
{
int inputs[3], a, b, c, d, x, x1, x2, i, lastDigit;
char *os, *noSol = "No solution\n", *cont = 'y';
while (cont == 'Y' || cont == 'y')
{
printf("This program solves a quadratic equation\n");
for (i = 1; i <= 3; i++)
{
lastDigit = i % 10;
if (i >= 4 && i <= 20)
os = "th";
if (i == 1 || lastDigit == 1)
os = "st";
else if (i == 2 || lastDigit == 2)
os = "nd";
else if (i == 3 || lastDigit == 3)
os = "rd";
else
os = "th";
printf("Enter your %d%s number: ", i, os);
scanf("%d", &inputs[i - 1]);
}
a = inputs[0];
b = inputs[1];
c = inputs[2];
while (1)
{
if (a == 0)
{
if (b == 0)
{
printf(noSol);
break;
}
else
{
x = -c / b;
printf("The equation is not quadratic and the solution is %d\n", x);
break;
}
}
else
{
d = pow(b, 2) - 4 * a * c;
if (d < 0)
{
printf(noSol);
break;
}
else if (d == 0)
{
x1 = -b / 2 * a;
printf("One solution: %d\n", x1);
break;
}
else if (d > 0)
{
x1 = (-b + sqrt(d)) / 2 * a;
x2 = (-b - sqrt(d)) / 2 * a;
printf("Two solutions: %d and %d\n", x1, x2);
break;
}
}
}
printf("Run program second time? ( Y / N )\n");
scanf("%s", &cont);
}
getch();
}

Many issues
The math part should use double (or float) instead of int.
double inputs[3], a, b, c, d, x, x1, x2;
printf() & scanf() for double, format specifier needs to change from %d to %le (or the like) to match double.
Math error: in 3 places, / 2 * a; should be / (2 * a);
char *cont = 'y' should be char cont[2] = "y"
scanf("%s", &cont); should be scanf("%1s", cont);.
Error handling: the return value of scanf() should be checked as in
if (1 != scanf("%lf", &inputs[i - 1])) { ; /* Handle error */ }
Minor math: if (d == 0) case results in a "double root", not a single solution. Practically speaking, given floating point math rounding, one does not always know d should have been mathematically exactly zero and thus the "single" root is really 2 very close roots. Further, with select values, the "Two solutions" will have the same value should sqrt(d) be much much smaller than b.

Related

Issue in calculating LCM of two -ve numbers or if either one is negative in C lang

The code is running perfectly for finding
LCM of 2 and 3 , LCM of 0 and 2 BUT
not able to execute for (-2 and 3) or (-2 and -3). I have written code for this type.
Check else if block that's the problem.
I expect LCM of -2 and -3 to get printed as 6. And LCM of -2 and 3 to get printed as 6.
#include <stdio.h>
int main()
{
int a,b;
printf("\n\t\t\t\t\tThis program calculate LCM of two numbers");
printf("\nEnter two numbers: ");
scanf("%d%d",&a,&b);
int i=0;
if(a!=0 && b!=0)
{
if(a>0 && b>0)
{
for(i=1; i<=a*b; ++i)
{
if((i%a==0)&&(i%b==0))
break;
}//for loop end
printf("LCM is %d",i);
}
else if(a<0 || b<0) //if any one number is -ve or both are -ve
{
// while(1)
// {
// int max = (a > b) ? a : b;
// if ((max % a == 0) && (max % b == 0))
// {
// printf("The LCM of %d and %d is %d.", a, b, max);
// break;
// }
// ++max;
// }
//Above commented portion not working for -ve numbers. This is my issue.
}
}
else
{
printf("LCM is %d",i);
}
return 0;
}
Potential infinite loop
When (max % a == 0) && (max % b == 0) is not true, loop goes on forever.
// OP's code
while(1) {
int max = (a > b) ? a : b; // Did OP want this before the loop?
if ((max % a == 0) && (max % b == 0)) {
printf("The LCM of %d and %d is %d.", a, b, max);
break;
}
++max; // This line serves no purpose.
}
Since OP wants a positive result, consider 1) using the absolute value of both arguments. 2) Use long long math to avoid int overflow in the absolute value and in a*b.
There are faster approaches than iterating [1...a*b].

How to display and add all even numbers?

How can I display and add all even numbers? The current code displays numbers between 2 numbers in an ascending manner.
#include <stdio.h>
main() {
int a;
int b;
printf("Enter integer a:");
scanf("%d", &a);
printf("Enter integer b:");
scanf("%d", &b);
if(b > a)
{
do {
printf("Result: %d\n", b);
b--;
} while (a <= b);
}
else
{
do {
printf("Result: %d\n", a);
a--;
} while (a >= b);
}
}
To check if an integer is even you can check if the least significant bit is zero.
To check if an integer is odd you can check if the least significant bit is one.
You can do that using bitwise AND (&).
Something like:
if(b > a)
{
if (b & 1) b--; // Make b even
if (a & 1) a++; // Make a even
int sum = 0;
do
{
sum += b;
printf("b is %d, sum is %d\n", b, sum);
b = b - 2;
} while (b >= a);
}
All even numbers are divisible by 2. You need to check if the remainder of division by 2 is equal to zero. In order to do it, you can use the modulo operator (%).
To display only even numbers:
if ((b%2) == 0) {
printf("Result: %d\n", b);
}
I'd write a function which I could test for different possible combinations of the extremes:
#include <stdio.h>
void evens(int a, int b)
{
// Make sure to always start from the greatest value.
if ( a > b ) {
int tmp = a;
a = b;
b = tmp;
}
// Make sure to always start from an EVEN value.
if ( b % 2 != 0 ) {
--b;
}
int sum = 0;
while ( a <= b ) {
printf("%d ", b);
sum += b;
b -= 2; // Jump directly to the previous even number.
}
printf("\nSum: %d\n", sum);
}
int main(void)
{
// Those should all print "10 8 6 4 2 \nSum: 30\n"
evens(1, 10);
evens(10, 1);
evens(2, 11);
evens(11, 1);
evens(2, 10);
}

divide a 4-digit integer into 2-digit integers and calculate by c

//Enter a 4-digit integer n from the keyboard, and write a program to divide it into two 2-digit integers a and B. Calculate and output the results of the addition, subtraction, multiplication, division and redundancy operations of the split two numbers. For example, n=-4321, if the two integers after splitting are a and b, then a=-43 and b=-21. The result of division operation requires that it be precise to 2 decimal places, and the data type is float. Redundancy and division operations need to take into account the division of 0, that is, if the split B = 0, then output the prompt information "The second operator is zero!"
//Failure to pass the test,how should i fix
#include<stdio.h>
#include<math.h>
int main()
{
int x, a, b;
printf("Please input n:\n");
scanf("%d", &x);
a = x / 100;
b = x % 100;
printf("%d,%d\n", a, b);
printf("sum=%d,sub=%d,multi=%d\n", a + b, a - b, a*b);
if (b == 0)
printf("The second operater is zero!");
else
printf("dev=%.2f,mod=%d\n", (float)a / b, a%b);
}
You forgot to check that x is a 4-digits number. So if the input is 12345 or 123 you don't satisfy the requirement.
#include <stdio.h>
int main()
{
int x, a, b;
int passed = 0;
// Enter a 4 digits number: ABCD
do {
printf("Enter X = ");
scanf("%d", &x);
passed = (x >= 1000 && x <= 9999) || (x >= -9999 && x <= -1000);
} while (!passed);
a = x / 100;
b = x % 100;
printf("Numbers: %d %d \n", a, b);
printf("Sum = %d \n", a + b);
printf("Sub = %d \n", a - b);
printf("Mul = %d \n", a * b);
if (0 == b) {
printf("Div by Zero \n");
} else {
printf("Div = %f \n", (double)a / b);
printf("Mod = %d \n", a % b);
}
return 0;
}

Types In C Displaying Imaginary Numbers

I have a question about types in C and I think it has to do with "real's"... This program is a quadratic equation solver and the user inputs a, b, and c in terms of ax^2 + bx + c = 0. My program works and I am sorry for lake of comments in the code so I will try to be very specific in my question. If you enter say 2, 2, 2 the discriminate of the quadratic is negative meaning no real answers or "imaginary numbers" (oh good old algebra days). So when you do this you get something like this
Specific part in code where this happens:
(First else in the while loop)
discriminate = b*b - 4 * a*c;
if (discriminate < 0)
{
root1 = (-b + sqrt(discriminate)) / (2 * a);
root2 = (-b - sqrt(discriminate)) / (2 * a);
printf("\nNOTE: Roots are not real.\n");
printf("The roots are, %.3f, and %.3f\n", root1, root2);
break;
}
So my question is two parts.
1) What is -1.#IO, and -1.#IO mean? (I know what it means) but what is #IO
2) How can I display the number properly? Is there a way?
FULL CODE:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
int main(void)
{
//declarations
float a;
float b;
float c;
float root1, root2;
int count;
float discriminate;
//Initialization
count = 0;
//starting propmts
printf("\nHello, this program will compute the real roots");
printf("of a quadratic equation.\n");
printf("In terms of a(x)^2 + b(x) + c = 0\n");
printf("\nPlease enter in the \"a\" value: ");
scanf("%f", &a);
printf("Please enter in the \"b\" value: ");
scanf("%f", &b);
printf("Please enter in the \"c\" value: ");
scanf("%f", &c);
while (count == 0)
{
if (a == 0)
{
if (a == 0 && b == 0)
{
printf("There is no soultion...\n");
break;
}
else
{
root1 = (-c / b);
printf("\nNOTE: Input is not quadratic but uesing \"(-c / b)\" ");
printf("the root is %.3f\n", root1);
break;
}
}
else
{
discriminate = b*b - 4 * a*c;
if (discriminate < 0)
{
root1 = (-b + sqrt(discriminate)) / (2 * a);
root2 = (-b - sqrt(discriminate)) / (2 * a);
printf("\nNOTE: Roots are not real.\n");
printf("The roots are, %.3f, and %.3f\n", root1, root2);
break;
}
else
{
root1 = (-b + sqrt(discriminate)) / (2 * a);
root2 = (-b - sqrt(discriminate)) / (2 * a);
if (root1 == root2)
{
printf("The root is, %.3f.\n", root1);
break;
}
else
{
printf("The roots are, %.3f, and %.3f.\n", root1, root2);
break;
}
}
}
}
printf("Goodbye.\n");
return 0;
}
MY CODE:
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
float a,b,c,d,x,y,i,j;
clrscr();
printf("\t\t\t QUADRATIC EQUATION SOLVING\n");
printf("Enter the co-efficients of x^2,x and constant \n");
scanf("%f%f%f",&a,&b,&c);
d=(b*b)-(4*a*c);
if(d>=0)
{
x=(-b+sqrt(d))/(2*a);
y=(-b-sqrt(d))/(2*a);
printf("The roots of the equation are %.2f %.2f",x,y);
}
else
{
d*=-1;
i=b/(2*a);
j=sqrt(d)/(2*a);
printf("The roots are %.2f+%.2fi and %.2f-%.2fi",i,j,i,j);
}
getch();
}
If the discriminant is less than zero, then you have some extra work to do. With the current code, you take the square root of a negative number, and the result should be not-a-number (NAN). I'm not sure why the printf doesn't just say that.
To fix the problem, you need to take the square root of the negative of the discriminant. Then you need to calculate the real and imaginary parts of the answer and display them as a complex number. Note that printf doesn't have any built-in support for complex numbers, so you have format the number yourself, e.g.
printf( "%f + %f i", realpart, imagpart );
If the discriminant is less than zero, then you have 2 complex roots. If the discriminant is greater than zero, then you have 2 real roots. If the discriminant is zero, then you have one real root.
if (discriminate < 0)
{
float rootr = -b / (2 * a);
float rooti = sqrt(-discriminate) / (2 * a);
printf("\nNOTE: Roots are not real.\n");
printf("The roots are, %.3f + %.3f i, and %.3f - %.3f i\n",
rootr, rooti,
rootr, rooti);
break;
}
else if(discriminate > 0)
{
float s = sqrt(discriminate);
float root1 = (-b + s) / (2 * a);
float root2 = (-b - s) / (2 * a);
printf("The roots are, %.3f, and %.3f.\n", root1, root2);
break;
}
else
{
float root = -b / (2 * a);
printf("The root is, %.3f.\n", root);
break;
}

equation solver in C segmentation fault

#include <stdio.h>
int main()
{
printf("choose number");
c();
}
c()
{
printf("1. ax+b=0\n\n");
printf("2. ax+by+c=0\n dx+ey+f=0\n\n");
int n;
scanf("%d", &n);
if (n > 3)
wrong();
if (n == 1)
formula1();
if (n == 2)
formula2();
if (n == 3)
;
formula3();
}
wrong()
{
printf("Please choose a number between 1 and 3.\n\n");
c();
}
formula1()
{
printf("ax+b=0\n");
printf("Enter your values for a and b respectively, seperated by commas\n");
float a, b, x;
scanf("%f,%f,%f", &a, &b);
x = -b / a;
printf("x=-b/a\n");
printf("=>x=%f", x);
question();
}
formula2()
{
printf("ax+by+c=0\n\ndx+ey+f=0\n");
printf(
"Enter your values for a, b, c, d ,e and f respectively, seperated by commas\n");
float a, b, c, d, e, f, x, y;
scanf("%f,%f,%f,%f,%f,%f", &a, &b, &c, &d, &e, &f);
x = ((f * b) - (c * e)) / ((a * e) - (d * b));
y = ((c * d) - (f * a)) / ((e * a) - (d * b));
printf("=>x=%f", x);
printf("\n\n");
printf("=>y=%f", y);
question();
}
question()
{
char t;
printf("\n\nanother equation?\ny/n?\n");
if (t == 'y')
{
printf("\n\n\n\n\n");
c();
}
else if (t != 'n')
question();
}
I have this code, which in short solves 3 equations.
When you select any choice it seems to run the question method multiple times then quits due to a segmentation fault: 11
Could someone please point out where I am going wrong. Any other help with my code would be greatly appreciated
Here is one problem:
scanf("%f,%f,%f",&a, &b);
Only two arguments are supplied for the three values.
There is no input function like scanf() in question() and so if t is not 'y' or 'n' by chance, you get an endless recursion until stack size is exceeded ...

Resources