C++: handling errors, can't understand my mistake [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
1.Check the user input. If the input does not match three floating-point numbers, output an error message and do not start the calculation.
2.Check whether a==0. If so, throw a runtime_error and catch it in main, printing a message saying that a must not be 0.
The error messages should look like this:
An error occured: Malformed user input
An error occurred: a must not be zero
#include <iostream>
#include <cmath>
#include <vector>
#include <stdexcept>
using namespace std;
vector<double> solutionFinal (double a, double b, double c){
double s1, s2, discriminant;
discriminant = b*b - 4*a*c;
if (discriminant > 0){
s1 = (-b + sqrt(discriminant)) / (2*a);
s2 = (-b - sqrt(discriminant)) / (2*a);
cout << "There are 2 solutions." << endl;
cout << "The solutions are: " << s1 << " and " << s2;
return {s1, s2};
}
else if (discriminant == 0) {
cout << "There is 1 solution." << endl;
s1 = (-b + sqrt(discriminant)) / (2*a);
cout << "The solution is: " << s1;
return {s1};
}
else {
cout << "There is no solution." << endl;
return {};
}
}
int main (){
double a, b, c;
cout << "Please enter the values of a, b, and c respectively:" << endl;
try{
if (!(cin >> a >> b >> c)) {
throw runtime_error("An error occured: Malformed user input");
}
if (a == 0) {
throw runtime_error("An erorr occured: a must not be zero");
}
}
auto result = solutionFinal(a, b, c);
for (auto scalar : result){
}
catch (runtime_error& excpt) {
cout << excpt.what();
}
return 0;
}

Your code is malformed, your braces don't add up. I prefer another brace style because I think it's easier to see that way:
#include <iostream>
#include <cmath>
#include <vector>
#include <stdexcept>
using namespace std;
vector<double> solutionFinal (double a, double b, double c)
{
double s1, s2, discriminant;
discriminant = b*b - 4*a*c;
if (discriminant > 0)
{
s1 = (-b + sqrt(discriminant)) / (2*a);
s2 = (-b - sqrt(discriminant)) / (2*a);
cout << "There are 2 solutions." << endl;
cout << "The solutions are: " << s1 << " and " << s2;
return {s1, s2};
}
else if (discriminant == 0)
{
cout << "There is 1 solution." << endl;
s1 = (-b + sqrt(discriminant)) / (2*a);
cout << "The solution is: " << s1;
return {s1};
}
else
{
cout << "There is no solution." << endl;
return {};
}
}
int main ()
{
double a, b, c;
cout << "Please enter the values of a, b, and c respectively:" << endl;
try
{
if (!(cin >> a >> b >> c))
{
throw runtime_error("An error occured: Malformed user input");
}
if (a == 0)
{
throw runtime_error("An erorr occured: a must not be zero");
}
// this block was outside the try, between the try and the catch.
// it MUST be inside the try block like this
auto result = solutionFinal(a, b, c);
for (auto scalar : result)
{
}
}
catch (runtime_error& excpt)
{
cout << excpt.what();
}
return 0;
}

Related

Wrong root from quadratic equation calculator

I was wondering if someone could help me in this problem.
So i tested the code but it didn't show the right answer below for
equation result of x2 + 5x + 6
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
double roots() {
double a, b, c, x1, x2;
cout << "Enter quadratic equation in order (a, b, c): \n";
cin >> a >> b >> c;
double discriminant = b * b - 4 * a * c;
x1 = -b + sqrt(discriminant) / 2 * a;
x2 = -b - sqrt(discriminant) / 2 * a;
if (discriminant >= 0 && a > 1) {
cout << "Your quadratic equation is " << a << "x^2 + " << b << " x + " << c << '\n';
cout << "x1 = " << x1 << '\n';
cout << "x2 = " << x2 << '\n';
}
else if (a == 1) {
cout << "Your quadratic equation is " << "x^2 + " << b << " x + " << c << '\n';
cout << "x1 = " << x1 << '\n';
cout << "x2 = " << x2 << '\n';
}
else {
cout << "Negative value returned from (b2 - 4ac), please try again!";
exit(1);
}
}
int main() {
roots();
}
You have the formula incorrect. Try this
x1 = (-b + sqrt(discriminant)) / (2 * a);
x2 = (-b - sqrt(discriminant)) / (2 * a);
Notice the extra parenthesis in order to put 2*a in the denominator and have it divide both b and the sqrt().
You also need to check if discriminant >= 0 before doing so, because if it is negative there is no root and the above lines are going to fail.
Firstly, using namespace std was not used, so if you don't want to use it write std::court and std::cin. Secondly, the formula is b^2 -4ac so you need to put round brackets around b*b so that the answer is subtracted from -4ac. Then, you don't need to write else if for a==1 you can add it in the above condition as a>=1 and else put down a condition where discriminant is >=0 but a==0 which violates quadratic eq condition and you can write a cannot be equal to zero. Also, the main formula for x1 and x2 is wrong since the bracket should be applied around -b+sqroot(discriminant) so that the answer is then divided by multiplication of (2*a). Otherwise, what happens is that first sqrt is divided by 2 then multiplied by a and then added to -b.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
double roots() {
double a, b, c, x1, x2;
std::cout << "Enter quadratic equation in order (a, b, c): \n";
std::cin >> a >> b >> c;
double discriminant = (b * b)- (4 * a * c);
x1 = (-b + sqrt(discriminant)) / (2 * a);
x2 = (-b - sqrt(discriminant))/ (2 * a);
if (discriminant >= 0 && a >= 1) {
std::cout << "Your quadratic equation is " << a << "x^2 + " << b << " x
+ " << c << '\n';
std::cout << "x1 = " << x1 << '\n';
std::cout << "x2 = " << x2 << '\n';
}
else if (a==0){
std::cout << "a cannot be zero!";
exit(1);
}
else{
std::cout << "Negative value returned from (b2 - 4ac), please try again!";
exit(1);
}
}
int main() {
roots();
}

Program that finds the number you are thinking doesn't work properly, what is wrong?

Im having trouble with this recursion code. Basically I want the computer to "guess" in as little steps as possible the number that I am thinking of. However, everything works except the final output. The bounds are fine, and it narrows down the guess until it asks me if the number im thinking of is say 16, if I input "=" it should output 16 instead it always outputs 50. Could anyone help me locate the error?
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
unsigned int search (unsigned int boundInf, unsigned int boundSup);
int main ()
{
int b;
b = search (1, 100);
cout << "Your number must be : " << b << endl;
}
unsigned int search (unsigned int boundInf, unsigned int boundSup)
{
string magnitude;
int b;
b = (boundSup + boundInf) / 2;
cout << "Is your number <, > or = to " << b << "? ";
cin >> magnitude;
if (magnitude == "<") {
cout << "Between " << boundInf << " and " << b << endl;
search (boundInf, b);
}
else if (magnitude == ">") {
cout << "Between " << b << " and " << boundSup << endl;
search (b, boundSup);
}
return b;
}
You forgot to change the value of b when going deeper into the recursive function, this can be easily fixed by changing the search function like so:
unsigned int search(unsigned int boundInf, unsigned int boundSup)
{
string magnitude;
int b;
b = (boundSup + boundInf) / 2;
cout << "Is your number <, > or = to " << b << "? ";
cin >> magnitude;
if (magnitude == "<")
{
cout << "Between " << boundInf << " and " << b << endl;
b = search(boundInf, b);
}
else if (magnitude == ">")
{
cout << "Between " << b << " and " << boundSup << endl;
b = search(b, boundSup);
}
return b;
}

Recursive function showing segmentation issue C++

This code is for recursive function practice. When I run the code, it stops at the "POWER" cout line, then my compiler shows a segmentation error. The function that follows the POWER line is supposed to recursively raise number "a" to the power of number "b". I'm not sure how to fix this, can anyone help?
#include <iostream>
#include <string>
#include <vector>
using namespace std;
/**** Recursive backwards print, prints a string starting from last index to first*****/
void printReverse(string s, int i)
{
if(i < s.size())
{
printReverse(s.substr(1), i);
cout<<s[i];
}
else
{
return;
}
}
/**** Recursive power function, computes a^b, where b can be positive or negative*****/
int recPower(double a, int b)
{
int i = b; //i = b, so int a can be multiplied int b times
if (i == 0) //base
return 1;
else //multiply A by B, B times
{
a *= b;
return recPower(a, b); //recursive
i--; //decrement i until it equals 0
}
}
/**** Recursive string replace, replaces all instances of a character in a string with another character*****/
string recReplace(string s2, int i, char old, char neW)
{
if(s2[i] == old) //search for old char
{
i = neW; //replace it
i++; //iterate i
}
recReplace(s2, i, old, neW); //call function
return s2;
}
/**** Recursive list find > Searches if x exists in list, returns true if found, false otherwise*****/
int recListFind(vector<int> v, int i, int x)
{
if(v[i] == x)
{
cout << x << " exists in the vector."<<endl;
i++;
recListFind(v, i, x);
}
return true;
}
int main()
{
cout << "PRINT REVERSE" << endl;
cout << "----------" << endl;
string s1 = "hello world";
cout << "String: " << s1 << endl;
cout << "Reversed: ";
printReverse(s1, 0);
cout << endl;
/* Computes a^b (power function) */
cout << "POWER" << endl;
cout << "----------" << endl;
int a = 2, b = -3;
cout << a << "^" << b << " = ";
cout << recPower(a, b) << endl;
cout << endl;
/* Replaces a character in a string with a new one */
cout << "REPLACE" << endl;
cout << "----------" << endl;
string s2 = "-h-e-l-l-o-";
char oldChar = '-';
char newChar = ' ';
cout << "String: " << s2 << endl;
cout << "> Replace '" << oldChar << "' with '" << newChar << endl;
recReplace(s2, 0, oldChar, newChar);
cout << "String: " << s2 << endl;
cout << endl;
/* Searches for value in vector */
cout << "FIND" << endl;
cout << "----------" << endl;
int x = 7;
cout << "Does " << x << " exist in the vector? "; vector<int> v = {5, 1, 6, 7, 9};
cout << recListFind(v, 0, 7) << endl;
cout << endl;
return 0;
}
The issue is quite straight forward, you are doing the recPower function with b. In the function, if b is not 0, you call recPower with an unmodified value of b (whilst ever modifying a). This will always end up with infinite recursion which is going to overflow your stack.
A solution could be:
int recPower(double a, int b, int times) {
if (times == 0)
return a;
else
return b * recPower(a, b, --times);
}
int recPower(double a, int b) {
return recPower(a, b, b);
}
Even if you fix this, you have another problem. b can be negative, which based on your logic will continue to recurse while decrementing until it overflows and goes back to 0. You will cause this case with your first test case. You should think about the types that are allowed in this function, consider making them unsigned, or dealing explicitly with the negative b case.

C++ statement is ignored in function

I have this test program and it seems like some statements inside a function (gcd()) are ignored. The std::cout statement seems to be ignored since nothing is printed to the screen with that statement. The if statement seems to be ignored because a and b were less than zero and b was positive whether that if statement was there or not (a and b remained the same).
I can't figure out why. Why are the two statements marked (with comment) are ignored?
#include <iostream>
#include <boost/multiprecision/cpp_int.hpp>
template <typename T> T gcd(T a, T b)
{
T remainder{a % b};
while (remainder != 0)
{
a = b;
b = remainder;
std::cout << remainder << '\n'; // ignored
remainder = a % b;
}
if (a < 0 && b < 0) b *= -1; // ignored
return b;
}
int main(int argc, char* argv[])
{
if (argc != 3)
{
std::cerr << '\n' <<
"Invalid number of argument(s)\n" <<
'\n' <<
"Usage: [number] [number]\n" <<
'\n';
return -1;
}
boost::multiprecision::cpp_int a{0}, b{0};
try
{
a = boost::multiprecision::cpp_int{argv[1]};
b = boost::multiprecision::cpp_int{argv[2]};
}
catch (...)
{
std::cerr << '\n' <<
"Invalid argument(s) or numbers too large/small\n" <<
'\n' <<
"Usage: [number] [number]\n" <<
'\n';
return -1;
}
const boost::multiprecision::cpp_int vgcd = gcd(a, b); // call to gcd()
std::cout << '\n' <<
"GCD (Greatest Common Divisor) test program using Euclid's algorithm (iterative)\n" <<
'\n' <<
"GCD(a, 0) = a\n" <<
"GCD(a, b) = GCD(b, a % b)\n" <<
'\n' <<
"GCD = " << vgcd << " Simplified fraction: " << a / vgcd << " / " << b / vgcd << '\n' <<
'\n';
}
You didn't actually call your gcd. boost::multiprecision provides its own gcd function, which is a better match than your template and picked up by ADL in your gcd(a, b).
Suppress ADL with ::gcd(a, b) or (gcd)(a, b) and you'll see your function template get called.

C++ Programming, Cannot understand errors

I am a beginner at c++ programming, and this is only my second program. I am getting a consistent error of "expected unqualified-id before..." idk what it means and cannot solve it. This is on lines 21,27,29,33,35,38,40,43,45.48,54,56,59,61,64,66,70.
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <math.h>
using namespace std;
int main ();
int a, b, c, x,y;
int discriminant;
double x1, x2;
int countdataisinvalid=0;
int countdataisvalid=0;
int countnolastterm=0;
int countonexvalue=0;
int countnomiddleterm=0;
int counttwoxterms=0;
while(!cin.eof)
{
a*x*x+b*x+c;
}
if (a==0),
countdataisinvalid++;
{
cout << "A is 0, data invalid." << endl;
}
else if, (discriminant < 0),
countdataisinvalid++;
{
cout << "The square is a negative number, data invalid." << endl;
}
else,
countdataisvalid++;
{
cout << " Data set is valid." << endl;
}
if (c==0),
countnolastterm++;
{
cout << "C is 0, there is no last term." << endl;
}
{
x1 = (-b + sqrt(b*b-4*a*c))/(2*a);
x2 = (-b - sqrt(b*b-4*a*c))/(2*a);
cout.precision(3);
}
if (x1==x2),
countonexvalue++;
{
cout << "Only one x value." << endl;
}
else, if (x1==-x2),
countnomiddleterm++;
{
cout << "There is no middle term." << endl;
}
else
counttwoxterms++;
{
cout << "There are two x values." << endl;
}
{
y = a*x1*x1+b*x1+c
y = a*x2*x2+b*x2+c
cout << "When x is " << x << "y is " << y << endl;
}
Your code contains too many errors. You should learn C++ again with writing simple programs.
At least this code compiles.
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <math.h>
using namespace std;
int main ()
{ // use { to begin definition of function, not ;
// initialize ariables for in case the reading fails
int a = 0, b = 0, c = 0, x = 0, y = 0;
int discriminant = 0;
double x1 = 0, x2 = 0;
int countdataisinvalid=0;
int countdataisvalid=0;
int countnolastterm=0;
int countonexvalue=0;
int countnomiddleterm=0;
int counttwoxterms=0;
// you should read numbers instead of writing possibly infinite loop and meaningless statement
cin >> a >> b >> c >> x >> discriminant >> x1 >> x2;
if (a==0) // remove extra comma
{
countdataisinvalid++; // move this statement to right position
cout << "A is 0, data invalid." << endl;
}
else if (discriminant < 0) // remove extra commas
{
countdataisinvalid++; // move this statement to right position
cout << "The square is a negative number, data invalid." << endl;
}
else // remove extra comma
{
countdataisvalid++; // move this statement to right position
cout << " Data set is valid." << endl;
}
if (c==0) // remove extra comma
{
countnolastterm++; // move this statement to right position
cout << "C is 0, there is no last term." << endl;
}
{
x1 = (-b + sqrt(b*b-4*a*c))/(2*a);
x2 = (-b - sqrt(b*b-4*a*c))/(2*a);
cout.precision(3);
}
if (x1==x2) // remove extra comma
{
countonexvalue++; // move this statement to right position
cout << "Only one x value." << endl;
}
else if (x1==-x2) // remove extra commas
{
countnomiddleterm++; // move this statement to right position
cout << "There is no middle term." << endl;
}
else
{
counttwoxterms++; // move this statement to right position
cout << "There are two x values." << endl;
}
{
y = a*x2*x2+b*x2+c; // add semicolon and remove useless statement
cout << "When x is " << x << "y is " << y << endl;
}
return 0; // add a statement to return some value
} // add this as end of definition of function