c++ quadratic equation not working properly for a code checker - c++

I am submitting code to my university's tester, the code for me works thoroughly for the the test cases I provided.
The checker tells there are some test cases that can't pass, I am testing in visual studio, and that's exactly compatible with the online judge compiler.
The problem description:
input : Contains 3 integer numbers: a,b,c (|a,b,c|<=1000).
output; The number of the equation's roots, then all roots in an ascending order. If you cannot do this, output "-1".
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
int a, b, c, delta;
double x1, x2, x;
cin >> a >> b >> c;
delta = ((b*b) - (4 * a * c));
if (a == 0) {
if (b != 0) {
x = (-(c)*1.0 / (b));
cout << 1 << " " << x;
}
else
cout << "-1";
}
else
if (delta > 0)
{
x1 = ((-(b + sqrt(delta))*1.0) / (2 * a));
x2 = ((-(b - sqrt(delta))*1.0) / (2 * a));
if (x1 <= x2) {
cout << 2 << " " << x1 << " " << x2;
}
else
cout << 2 << " " << x2 << " " << x1;
}
else if (delta == 0)
{
x = (-(b)*1.0 / (2 * a));
cout << 1 << " " << x;
}
else
cout << "-1";
return 0;
}
I can't find any test case that fails my program, please if you can find some test cases, hints whatever I am just stuck at the problem. Thanks

the example output is described as follows; intput: 1 -8 15 output: 2 3 5
If the input was -1 8 -15, this program would output 2 5 3, while the two solutions are requested to be printed in ascending order. So you need to sort them before printing. Also I'd add a newline to every output statement.
-edit-
Without knowing the exact format required and the numbers in the failing tests, we can only speculate on how to modify the posted program. Some changes, though, could be beneficial.
I/O
There isn't any check of the input. On-line judges usually give well defined input, but you can always add some test.
cin >> a >> b >> c;
if (!cin)
cout << "-1\n";
I already mentioned the newline at the end of the line, another (unknown) requirement could be a particular precision of the outputted numbers (in fixed or scientific format).
In the comments I also pointed out the particular case of -0.0 or (-0), which while beeing a perfectly valid floating point value, could be for some reason rejected by the tester. Unlikely, but possible. So you could write the first case like this:
if (a == 0)
{
if (b != 0)
{
if ( c == 0 )
x = 0.0;
else
x = double(-c) / b;
cout << "1 " << x << '\n';
}
else
cout << "-1\n";
}
precision and corner cases
In the unlikely (given the ranges of the input values) case that you are running into precision issues, you could choose other formulas (see e.g. numerically stable algorithm for solving the quadratic equation).
else if (delta > 0)
{
if ( c == 0 )
{
x1 = 0.0;
x2 = double(-b) / a;
}
else
{
if ( b > 0 )
x1 = -0.5 * (b + std::sqrt(delta)) / a;
else
x1 = -0.5 * (b - std::sqrt(delta)) / a;
x2 = c / (a * x1);
}
if (x1 > x2)
cout << "2 " << x2 << " " << x1 << '\n';
else
cout << "2 " << x1 << " " << x2 << '\n';
}
The last part really boils down to how to consider two coincident solutions.
else if (delta == 0)
{
if ( b == 0 )
x = 0.0;
else
x = -0.5 * b / a;
cout << "1 " << x << '\n';
// Assuming they don't require ("all the roots")
// cout << "2 " << x << ' ' << x << '\n';
}

The problems would likely lie in the realm of int to double conversion.
To debug this, you need to separate out your operations into distinct lines the debugger can stop on. For instance the expression -(c*1.0) is better expressed as (double)-c. It at least makes it clearer and utilizes a negation (free) and cast (more precise [linguistically] than multiplication by 1.0).
So for instance, your code would become something like this :
#include <iostream>
#include <math.h>
using namespace std;
int mainC(int argc , char** argv)
{
(void)argc;
(void)argv;
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
int a, b, c, delta;
double x1, x2, x;
cin >> a >> b >> c;
delta = ((b*b) - (4 * a * c));
if (a == 0) {
if (b != 0) {
/// x = (-(c*1.0) / (b));
/// separate the operation and avoid multiplication and implicit casts
x = ((double)-c);
x /= (double)b;
cout << 1 << " " << x;
}
else
cout << "-1";
}
else
if (delta > 0)
{
/// x1 = ((-(b + sqrt(delta))*1.0) / (2 * a));
/// x2 = ((-(b - sqrt(delta))*1.0) / (2 * a));
/// separate the operation and avoid multiplication and implicit casts
// discriminant
const double discrim = sqrt(delta);
x = (double)-b;
x1 = x + discrim;
x2 = x - discrim;
x1 /= (double)(2*a);
x2 /= (double)(2*a);
cout << 2 << " " << x1 << " " << x2;
}
else if (delta == 0)
{
/// x = (-(b*1.0) / (2 * a));
/// separate the operation and avoid multiplication and implicit casts
x = (double)-b;
x /= (double)(2*a);
cout << 1 << " " << x;
}
else
cout << "-1";
return 0;
}

I think default cout precision does not math to your problem. Try
std::cout << std::setprecision(10);
or greater.
Also u can try use
std::cout << std::flush

Related

My function factoring program has problems with variables, shows incorrect answers

I'm making a program that factors functions (f(x), not fully factored though):
#include <iostream>
#include <math.h>
#include <stdio.h>
using namespace std;
int x3;
int x2;
int x;
int remain;
int r = 0;
int factor;
int main() {
int b, i, j = 0;
int factors[101];
cout << "f(x) = x^3 + x^2 + x + r (Factor tool)" << endl;
cout << "x^3?: ";
cin >> x3;
cout << "x^2: ";
cin >> x2;
cout << "x: ";
cin >> x;
printf("remain (Y intercept): ");
scanf("%d", &b);
cout << "f(x) = " << x3 << "x^3 + " << x2 << "x^2 + " << x << "x + " << b
<< "" << endl;
cout << "factors of remainder are: " << endl;
for (i = 1; i <= b; i++) {
if (b % i == 0) {
factors[j++] = i;
printf("%d\t", i);
}
}
getchar();
while (true) {
int good;
if (factors[1] == 0) {
cout <<endl;
cout << "Equation Cannot be factored";
break;
}
int factorv = factors[r];
int nx1 = x3 * factors[r];
int nx2 = (nx1 + x2);
int nx3 = x + (nx2 * factors[r]);
int nx4 = remain + (nx3 * factors[r]);
if (nx4 == 0) {
int factored = (0 - factors[r]);
cout <<endl;
cout << "The Factored Function: f(x) = "
<< "(x " << factored << ")(" << nx1 << "x^3 + " << nx2 << "x^2 + "
<< nx3 << "x"
<< ")"
<< "";
break;
} else {
r = r + 1;
}
}
}
but in this part of the code, it shows as (x 0)(0x^3 + (x3 input instead of calculated nx1)x^2 + (x2 input instead of calculated nx2)x).
if (nx4 == 0) {
int factored = (0-factors[r]);
cout<<"The Factored Function: f(x) = "<<"(x "<<factored<<")("<<nx1<<"x^3 + "<<nx2<<"x^2 + "<<nx3<<"x"<<")"<<"";
break;
What happen to my nx variables? Why is it coming up incorrect or as a 0 when it was calculated properly above?
You have some of your variables twice:
int nx1;
int nx2;
int nx3;
int nx4;
They exists as global variables and again in the scope of main. They have the same name but are different variables.
Take the lesson: Global variables are no good.
Moreover you have a logic error in your code. When I add a std::cout << r << std::endl; in the last while loop I see its value increasing until there is a segfault, because factors[r] is out-of-bounds. broken code # wandbox
I cannot really tell you how to fix it, because I would have to dive into the maths first. I can only suggest you to never use infinte loops in numerical codes without an "emergency exit". What i mean is that unless fully tested, you cannot be sure that the loop will end at some point and when it doesn't typically the consequences are bad and difficult to diagnose. Always make sure the loop will end at some point:
int max_iteratons = 100;
int counter;
while (counter < max_iteratons) {
// do something
++counter;
}
if (counter == max_iterations) std::cout << "i have a bug :(";

Quadratic equation solver outputting in unknown format

I'm trying to make a quadratic equation solver, but for some reason my program is giving me answers in an unknown format.
I entered the simple quadratic equation x^2 + 2x + 1 = 0, expecting my program to give x = -1 or x = -1, but instead it gave x = 0138151E or x = 0138152D. It looks like it outputs these values for x for any inputs (not recognizing unreal answers and catching them). Why is this and how can I fix it?
#include "../std_lib_facilities_revised.h"
class Imaginary {};
double square(int a)
{
return a * a;
}
double quadratic_solver_pos(int a, int b, int c)
{
double x = 0.0;
double radicand = square(b) - 4 * a * c;
if (radicand < 0) throw Imaginary{};
x = (-b + sqrt(radicand)) / (2 * a);
return x;
}
double quadratic_solver_neg(int a, int b, int c)
{
double x = 0.0;
double radicand = square(b) - 4 * a * c;
if (radicand < 0) throw Imaginary{};
x = (-b - sqrt(radicand)) / (2 * a);
return x;
}
int main()
try {
cout << "This program is a quadratic equation solver.\n";
cout << "Quadratic equations are of the form: ax^2 + bx + c = 0\n";
cout << "Enter a, b, and c, respectively:\n";
double a = 0;
double b = 0;
double c = 0;
cin >> a >> b >> c;
cout << "Your quadratic equation: " << a << "x^2 + " << b << "x + " << c << " = 0\n";
cout << "x = " << quadratic_solver_pos << " or x = " << quadratic_solver_neg << '\n';
}
catch (Imaginary) {
cout << "x is unreal\n";
}
You don't pass your variables to your functions.
You need to do it like so quadratic_solver_pos(a, b, c);.

error: operands to ?: have different types 'int' and 'std::basic_ostream<char>'

#include <iostream>
#include <cmath>
using namespace std;
int main(){
int a , b , c , D ;
double x1 , x2 ;
cout << " a = " ;
cin >> a;
cout << " b = " ;
cin >> b;
cout << " c = " ;
cin >>c;
D = pow(b,2) - 4 * a * c;
x1 = (-b + D ) / (2*a);
x2 = (- b - D) / (2*a);
cout << "D = " << D << endl;
D >= 0 ? ( x1,x2) : (cout << "nope . \n" , x1 = x2 = 0);
cout << x1 << endl;
cout << x2 << endl;
(D % 2) == 1 ? (D++) : (cout << "Number is even . \n" ); //check if number is uneven and if it is then add 1
cout << D << endl;
return 0;
}
it throws the error :operands to ?: have different types 'int' and 'std::basic_ostream' .
At the line where is the comment.
Is it possible to fix it by using the conditional operator (?) ?
As suggested in comments, cast both operands to void:
(D % 2) == 1 ? void(D++) : void(cout << "Number is even . \n" );
Or even better, use a regular if:
if (D % 2 == 1)
D++;
else
cout << "Number is even . \n";
You need to do the same thing for the other use of the ? : as well.
It has been said in the comments of the question already but to clarify on this.
The ternary(?) operator has a return type equal to the type of both code branches if the branches do not return the same type then this error will get shown by the compiler.
A comment use of the ternary operator is to assign a value to a variable depending on a condition:
bool isConnected = true;
static int idCount = 0;
int connectionID = isConnected ? ++idCount : -1;

Quadratic Formula c++ - user-defined function

I wrote this code with a user-defined function, but it seems not to work. I've trying to find out where the mistake is for hours. But couldn't find anything. it looks like the problem is in passing the parameter. But I don't know, I'm pretty new to this!
#include <iostream>
#include <cmath>
using namespace std;
double solutionFun (double a, double b, double c) {
double delta, solution1, solution2;
delta = b*b - 4*a*c;
if (delta > 0 ){
solution1 = (-b + sqrt(delta)) / (2*a);
solution2 = (-b - sqrt(delta)) / (2*a);
cout << "There are 2 solutions." << endl;
cout << "The solutions are:";
return solution1, solution2;
}
else if (delta == 0){
solution1 = (-b) / (2*a);
cout << "There is 1 solution." << endl;
cout << "The solution is:";
return solution1;
}
else {
cout << "There is no solution.";
return 0;
}
}
int main(){
double a ,b ,c;
cout << "Please enter the values of a, b, and c respectively:";
cin >> a ,b ,c;
solutionFun(a ,b ,c);
return 0;
}
A few issues with regards to code validity and desired behavior (coding practice/design aside):
See how to return multiple values from your solutionFun() (currently defined to return double) by using std::vector -- even though you are not using anything returned in this piece of code.
You didn't print (cout <<) the solution values themselves, and it seemed like you were going for it.
See how to use std::cin for multiple inputs in one line of code.
A fixed version -- with respect to the above points:
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
std::vector<double> solutionFun (double a, double b, double c) {
double delta, solution1, solution2;
delta = b*b - 4*a*c;
if (delta > 0 ){
solution1 = (-b + sqrt(delta)) / (2*a);
solution2 = (-b - sqrt(delta)) / (2*a);
cout << "There are 2 solutions." << endl;
cout << "The solutions are: " << solution1 << " and " << solution2;
return {solution1, solution2};
}
else if (delta == 0){
solution1 = (-b) / (2*a);
cout << "There is 1 solution." << endl;
cout << "The solution is: " << solution1;
return {solution1};
}
else {
cout << "There is no solution.";
return {};
}
}
int main(){
double a ,b ,c;
cout << "Please enter the values of a, b, and c respectively:";
cin >> a >> b >> c;
auto result = solutionFun(a ,b ,c);
for (auto scalar : result)
{
// Do something with a component, or don't return anything from the function : )
}
return 0;
}
This code is not how you get multiple inputs:
cin >> a ,b ,c;
Instead, you want:
cin >> a >> b >> c;
This code is not how you display answers:
cout << "The solutions are:";
return solution1, solution2;
Instead you want:
cout << "The solutions are:" << solution1 << " and also " << solution2;
Another method is pass your solution variables on the command line:
void solutionFun (double a, double b, double c,
double& solution1, double& solution2, size_t& solution_count) {
double delta;
delta = b*b - 4*a*c;
solution2 = 0.0;
if (delta > 0 ){
solution1 = (-b + sqrt(delta)) / (2*a);
solution2 = (-b - sqrt(delta)) / (2*a);
solution_count = 2;
cout << "There are 2 solutions." << endl;
cout << "The solutions are: " << solution1 << " and " << solution2;
return;
}
else if (delta == 0){
solution1 = (-b) / (2*a);
solution_count = 1;
cout << "There is 1 solution." << endl;
cout << "The solution is: " << solution1;
return;
}
else {
cout << "There is no solution.";
solution_count = 0;
return;
}
}
The solution1, solution2 and solution_count are passed by reference which means that the function can modify the caller's variables.

My c++ code for factoring isn't working

I am trying to create a c++ program that when I input two numbers (num1, combinationNum), it finds two numbers that multiply together to equal num1, but add together to equal combinationNum. It currently works for positive integers, but not negative. How do I make it work with negative integers? Also, If the equation isn't solvable, I would like it to print an error of some sort. Thanks!
Code:
//
// main.cpp
// Factor
//
// Created by Dani Smith on 2/13/14.
// Copyright (c) 2014 Dani Smith Productions. All rights reserved.
//
#include <iostream>
#include <cmath>
using namespace std;
void factors(int num, int comNum){
int a, b;
cout<<"The factors are ";
bool isPrime = true;
int root = (int)sqrt((double)num);
for(int i = 2; i <= root; i++){
if(num % i == 0 ){
isPrime = false;
//cout<<i<<",";
for(int x = 0; x<3; x++){
if(x==1){
a = i;
}
else if(x == 2){
b = i;
}
if(a + b == comNum){
cout << a << ", and " << b << ".";
}
}
}
}
//----------------------------------------
if(isPrime)cout<<"1 ";
cout<<endl;
}
int main(int argc, const char * argv[])
{
int num1 = 0, num2 = 0, multiple = 0, combinationNum = 0, output1 = 0, output2 = 0;
cout << "What number do you want to factor?\n";
cin >> num1;
cout << "What do you want them to add to?\n";
cin >> combinationNum;
factors(num1, combinationNum);
return 0;
}
To solve:
x + y == a
x * y == b
You have to solve
y == a - x
x * x - a * x + b == 0
So with delta == a * a - 4 * b, if delta positive, the solutions are
x1 = (a + sqrt(delta)) / 2
x2 = (a + sqrt(delta)) / 2
The code : (https://ideone.com/qwrSwa)
void solve(int sum, int mul)
{
std::cout << "solution for x + y = " << sum << std::endl
<< " x * y = " << mul << std::endl;
const int delta = sum * sum - 4 * mul;
if (delta < 0) {
std::cout << "No solution" << std::endl;
return;
}
const float sqrtdelta = sqrtf(delta);
const float x1 = (sum + sqrtdelta) / 2.f;
const float x2 = (sum - sqrtdelta) / 2.f;
std::cout << "x = " << x1 << ", y = " << sum - x1 << std::endl;
if (delta != 0) {
std::cout << "x = " << x2 << ", y = " << sum - x2 << std::endl;
}
}