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.
Related
This code solves the program : Create an algorithm in the form of a flowchart, write and debug the task using recursive and ordinary functions. Corresponding results.
What is dot used for here "x = (1. / 2) * (f + (a / f));" ?
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int k, e, x, a, d, n, f, s;
d = 1;
do {
e = 1;
do {
cout << "Press 1 to use recurrent solution method, press 2 to use nun recurrent solution
method" << endl;
cin >> k;
if (k == 1 || k == 2) e = 2;
} while (e == 1);
switch (k)
{
case 1:
{
cout << "Enter the numder a:" << endl;
cin >> a;
cout << "Enter the numder n:" << endl;
cin >> n;
x = (1. / 2)*(1 + a);
f = x;
s = f;
for (int i = 1; i < n; i++)
{
x = (1. / 2) * (f + (a / f));
s += x;
f = x;
}
cout << "Result: " << s << endl;
}
break;
case 2:
{
cout << " Enter the numder a:" << endl;
cin >> a;
x = sqrt(a);
cout << "Result: " << x << endl;
}
break;
}
cout << "Press 1 to repeat!" << endl;
cin >> d;
} while (d == 1);
}
The dot in "x = (1. / 2) * (f + (a / f));" is used for assuring that the division is interpreted as a float division instead of an integer division, so the result of (1/2) is 0.5 instead of 0.
#include <iostream>
#include <iomanip>
using namespace std;
//Power function
float power (float base, int exp)
{
if (exp < 0)
{
if (base == 0)
{
cout << "Base cannot be 0.";
return -1;
}
}
if (exp == 0)
return 1;
if (exp == 1)
return base;
return base * power (base, exp - 1);
}
//Factorial function
int facto (int n)
{
return n <= 0 ? 1 : n * facto (n - 1);
}
//Cos function
float cosCalc (float rad)
{
float cos = 0;
int x;
for (x = 0; x < 10; x++)
{
cos += power (-1, x) * power (rad, 2 * x) / facto (2 * x);
}
return cos;
}
//Sin function
float sinCalc (float rad)
{
float sin = 0;
int x;
for (x = 0; x < 10; x++)
{
sin += power (-1, x) * power (rad, 2 * x + 1) / facto (2 * x + 1);
}
return sin;
}
//Main function
int main()
{
int choice;
//Title and Menu
cout << endl << "==============" << endl << " TRIGONOMETRY " << endl << "==============";
cout << endl << "Select:";
cout << endl << "1. Calculate Cos and Sin";
cout << endl << "9. Exit";
while (true)
{
//User Prompt
cout << endl << endl << "Please enter your choice. => ";
cin >> choice;
if (choice == 1)
{
int angle, anglePh;
float rad;
float pi = 3.14159265358979323846264338327950288419716;
char angleType;
float cos = 0;
float sin = 0;
cout << endl << "Please enter an angle. => ";
cin >> angle;
anglePh = angle;
angle %= 360;
rad = angle * pi / 180;
cout << anglePh << " degrees = " << rad << " radian";
cout << endl << "Calculating Cos...";
cosCalc (rad);
cout << endl << "Cos = " << fixed << cos;
cout << endl << "Calculating Sin...";
sinCalc (rad);
cout << endl << "Sin = " << fixed << sin;
}
if (choice == 9)
{
break;
}
}
}
I am building a program that calculates Sin and Cos off an angle input, and when I run it, it outputs 0.000000 for both Sin and Cos. I suspect there is something to do with me declaring float cos = 0 and float sin = 0 in the if loop for choice == 1, and I tried messing around with it but it either results in the program straight out giving me errors on launch, or I get the same outputs.
Any idea where I went wrong?
Thanks for your insight in advance, cheers!
Your cosin and sine function return a float, but in order to get that result you still have to store it in a variable.
So instead of:
cosCalc (rad);
Do:
rad = cosCalc (rad);
and the same for your sine function.
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 :(";
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
I had a prior snag with this problem that was resolved but I felt that since the nature of my new issue is not related to successful compiling, rather to actual logic of the code, that it would be acceptable to make a new topic. Here is my code so far:
#include "assign4.h"
#include <iostream>
using namespace std;
int main(int argc, char * argv[]){
solution s;
double root;
cout << "Enter interval endpoints: ";
cin >> s.xLeft >> s.xRight;
cout << "Enter tolerance: ";
cin >> s.epsilon;
root = s.bisect (s.xLeft, s.xRight, s.epsilon, &solution::f, s.error);
if (!(s.error))
cout << "Root found at " << root << "\nValue of f(x) at root is: " << s.f(root) << "\n";
else {
cout << "The solution of a quadratic equation with coefficients: " << endl;
// cout << "a = " << a << ", b = " << b << ", c = " << c << endl;
cout << "has not been found." << endl;
}
return 0;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "assign4.h"
#include <iostream>
#include <math.h>
using namespace std;
double solution::bisect (double xLeft, double xRight, double epsilon, double (solution::*f)(double), bool& error) {
double xMid;
double fLeft, fRight;
double fMid;
fLeft = (this->*f)(xLeft);
fRight = (this->*f)(xRight);
error = (fLeft * fRight) < 0;
if (error)
return -999.0;
for (double i = 0; i < 20; i++) {
xMid = (xLeft + (xLeft + 1.0)) / 2.0;
fMid = (this->*f)(xMid);
if (fLeft * fMid > 0.0) {
xLeft = xMid + 0.5;
xRight = xLeft + 1.0;
fLeft = fMid;
}
else if (fLeft * fMid < 0.0){
xRight = xMid;
fRight = fMid;
}
else {
return xMid;
}
cout << "New Interval is [" << xLeft << ", " << xRight << "]" << endl;
}
return (xLeft + xRight) / 2.0;
}
double solution::f (double x) {
return ((1 * pow(x,2.0)) + (5 * x) + 2);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef ASSIGN4_H
#define ASSIGN4_H
class solution {
public:
double xLeft, xRight;
double epsilon;
bool error;
double bisect(double, double, double, double (solution::*f)(double), bool&);
double f(double);
};
#endif // ASSIGN4_H
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
My goal with this assignment is to find any roots should they exist. My issue is that every bisection example I have found only talks about how to find a single root at once. The interval I am to use is [-10.0, 10.0] and eventually I am going to receive coefficients of the equation passed via an array encapsulated in a structure, but for now I have hard coded the coefficients.
So my problem is that I can currently get with 0.2 of the first root for the equation I have hard coded (x^2 + 5x + 2) but I am uncertain of how to step past that root and keep searching for another root up until the end of my interval. I am also unsure of how to accurately hit the root and not be marginally off.
Apologies for the wall of text and any help is appreciated! :)
You can input the interval such that it includes both the roots. Then call bisect twice -- once for the lower root and once for the higher root.
int main(int argc, char * argv[]){
solution s;
double root;
cout << "Enter interval endpoints: ";
cin >> s.xLeft >> s.xRight;
cout << "Enter tolerance: ";
cin >> s.epsilon;
double xMid = 0.5*(s.xLeft + s.xRight);
root = s.bisect (s.xLeft, xMid, s.epsilon, &solution::f, s.error);
if (!(s.error))
cout << "Root found at " << root << "\nValue of f(x) at root is: " << s.f(root) << endl;
else
{
cout << "The solution of a quadratic equation with coefficients: " << endl;
cout << "has not been found." << endl;
}
root = s.bisect (xMid, s.xRight, s.epsilon, &solution::f, s.error);
if (!(s.error))
cout << "Root found at " << root << "\nValue of f(x) at root is: " << s.f(root) << endl;
else
{
cout << "The solution of a quadratic equation with coefficients: " << endl;
cout << "has not been found." << endl;
}
return 0;
}