In: Computer Science
home / study / engineering / computer science / questions and answers / i have a c++ question, its already posted on here ... Question: I have a c++ question, its already posted on here ... Bookmark I have a c++ question, its already posted on here but the answer given is way too complex and i dont understand it... its only the first month of c++ so please use the basic code... thank you.
Assume that ax^2 + bx + c = 0. We can now use the quadratic equation to find the value(s) of x. 1. Write a program that generates 3 seeded random integers ranging from -5 to 5 for the values of a, b and c. (You need to seed the random numbers) 2. If a is equal to 0, output “We cannot divide by 0” and do nothing. This is the end of the program. 3. If a is NOT equal to 0, then do the following: 3-1) If b^2– 4ac is positive, then you should output 2 possible values for x based on above equation 3-2) If b^2– 4ac is 0, then you should output 1 value for x. 3-3) Otherwise, you should output “No solution for x” Run the program five times to test. Make sure for each run the value for a, b, c changes.
#include <iostream>
#include <stdlib.h>
#include<time.h>
using namespace std;
int main() {
//initializes the seed
srand(time(NULL));
//initializes the variables
int a, b, c, d;
//generates random number between -15 and 5 for a
a = rand() % (5 - (-5) + 1) + (-5);
//this message is for checking you can comment out this is you
don't need it
cout << "a=" << a << endl;
//checks if the value of a is zero
if (a == 0) {
cout << "We cannot divide by 0" << endl;
//if true exits the program
return 0;
} else {
//if not zero then calculates random number for b and c
b = rand() % (5 - (-5) + 1) + (-5);
//this message is for checking you can comment out this is you
don't need it
cout << "b=" << b << endl;
//generates random number between -15 and 5 for c
c = rand() % (5 - (-5) + 1) + (-5);
//this message is for checking you can comment out this is you
don't need it
cout << "c=" << c << endl;
//calculates number of possible roots using b^2-4ac
d = (b * b)-(4 * a * c);
//this message is for checking you can comment out this is you
don't need it
cout << "d=" << d << endl;
//if d greater then zero - 2 roots
if (d > 0) {
cout << "root1: " << (-b - d) / 2 * a <<
endl;
cout << "root2: " << (-b + d) / 2 * a <<
endl;
}
//if d equal to zero - 1 root
else if (d == 0) {
cout << "root: " << (-b - d) / 2 * a <<
endl;
}
//if d less then zero - no roots
else {
cout << "No solution for x" << endl;
}
}
return 0;
}
outputs
test 1
test2
test3
test4
test5