c++ how to have a user input equation to be evaluated - c++

My program is meant to ask a user to input an equation. Then find the maximum over an interval given by the user. When I compile my program, the output I get is:
Please complete the equation to be evaluated f(x)=
Please enter the first number of the interval to be checked:
Please enter the last number of the interval to be checked:
Please enter the desired initial step size:
sh: PAUSE: command not found
with the last line repeating many times.
I think the problem here has something to do with having the user input the equation to be tested. However, I'm unsure of how to fix this.
Here's my code
#include <iostream>
#include <cmath>
#include <cstdlib>
using namespace std;
int main()
{
int a, b, delta, fx, x, y;
int max = 0;
cout <<"Please complete the equation to be evaluated f(x)= " << endl;
cin >> fx;
cout <<"Please enter the first number of the interval to be checked: " << endl;
cin >> a;
cout << "Please enter the last number of the interval to be checked: " << endl;
cin >> b;
cout << "Please enter the desired initial step size: " << endl;
cin >> delta;
for(x = a; x <= b; x = x+delta)
{
y = fx;
if (y > max)
{
max = y;
cout <<"The maximum over the interval from " << a <<"to " << b <<"is " << delta;
}
else
{
delta= delta/2;
}
if (delta < pow( 10, -6))
{
system ("PAUSE");
}
}
return 0;
}

F(x) shouldn't be an integer variable, it should be a string variable. That way, the user can enter operators as characters instead of the compiler thinking they should be numbers. You would then have to process the string to determine the equation; this would require some thought, and possibly a more advanced data structure such as a binary tree.

Simply don't use system("pause"); in the if statement and you'll lose that error:
"sh: PAUSE: command not found". Place it right before the end of the main.
system("pause");
return 0;

As pointed out by others, the form of f(x) could be an issue with the above code.
Consider to redesign what to achieve for your program. One possibility is to narrow down the f(x) as polynomial function so that you can avoid parsing general algebraic equation, in this case you can ask:
how many degree of the polynomial ? upon this, it is followed by input the coefficient value for each factor in the polynomial equation.
This way, you can still use integer (or double - better) in the program.

Related

Babylonian square root algorithm output not matching example

I'm doing an assignment and while I have it pretty much entirely done, I've run into a problem. The program is supposed to find the square root of a number the user inputs using the Babylonian square root algorithm. I was given an example output, and mine does not quite match. Also if you see any more issues please, give me a heads up! Especially if it's about the do while loop (it was the only solution I could get that stopped an infinite loop issue I was having).
#include <ios>
#include <iomanip>
#include <iostream>
using namespace std;
int main()
{
std::cout << std::fixed << std::setprecision(4);
//variables
int input;
double guess, r, check, test;
//input
cout << "Enter a number and I will apply the\n";
cout << "Babylonian square root algorithm until\n";
cout << "I am within .001 of the correct answer\n";
cin >> input;
cout << "You input " << input << "\n";
//calculate
guess = input / 2;
do {
test = guess;
r = input / guess;
guess = (guess + r) / 2;
cout << "\nguessing " << guess;
} while (guess != test); //while end
//check
check = guess * guess;
cout << "\nThe Babylons algorithm gives " << guess;
cout << "\nChecking: " << guess << " * " << guess << " = " << check << "\n";
} //main end
**Example output:**
Enter a number and I will apply the Babylonian square root algorithm
until I am withing .001 of the correct answer.
151
You entered 151
guessing 38.75
guessing 21.3234
guessing 14.2024
guessing 12.4172
guessing 12.2889
The Babylons algorithm gives 12.2889
Checking: 12.2889 * 12.2889 = 151.016
Press any key to continue . . .
**My Output:**
Enter a number and I will apply the
Babylonian square root algorithm until
I am within .001 of the correct answer
151
You input 151
guessing 38.5067
guessing 21.2140
guessing 14.1660
guessing 12.4127
guessing 12.2888
guessing 12.2882
guessing 12.2882
guessing 12.2882
The Babylons algorithm gives 12.2882
Checking: 12.2882 * 12.2882 = 151.0000
Change the type of input from int to double:
double input;
which changes initial value of guess = input / 2 from floor(151/2) = 75.0 to 75.5 for the expected sequence of values. Alternatively, cast the enumerator input to a double in the expression with:
guess = (double) input / 2;
or more elegantly via implicit type conversion by using floating point value as the divisor at suggested by #AlanBirtles:
guess = input / 2.0;
To fix the loop test:
#include <math.h>
...
do {
...
} while(fabs(test - guest) > 0.001);

Cin appears to be failing inside this loop. Can anyone explain what I'm doing wrong?

I'm getting a compiler error when trying to build the code below and I don't quite understand what is failing and why.
It's pointing to line 45 (cin>>x[ctr]) with a "no type named 'type' in 'struct std::enable_if<false, std::basic_istream&>'" message.
I've just started coding a few days ago and English is not my native language. Apologies if this question is below the community's paygrade. Hope you can point me in the right direction.
cpp.sh/34sm3
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <iomanip>
//#include "_pause.h"
using namespace std;
//////////////////////////////////////////////////////////////////
// NOTE
// This is your program entry point. Your main logic is placed
// inside this function. You may add your functions before this
// "main()", or after this "main()" provided you added reference
// before this "main()" function.
//////////////////////////////////////////////////////////////////
//Write a program that can divide six non-zero integers (two integers per division) from the user and display the result to the user.
//Create a function that will perform the division operation. Display only the non-decimal part of the quotient.
float quot (int num1, int num2)
{
return num1/num2;
}
int main()
{
// ************************** TO DO **************************
// Place your code logic after this comment line
// ***********************************************************
int x[6];
cout<<"Enter 6 integers to divide: ";
for(int ctr=0; ctr<6; ctr++)
{
cin>>[ctr];
if(x[ctr]==0)
{
cout<<"Invalid number! Please enter a non-zero value: ";
cin>>x[ctr];
}
}
cout<<"The quotient of the first pair is: " << quot(x[0],x[1]) <<endl;
cout<<"The quotient of the second pair is: " << quot(x[2],x[3]) <<endl;
cout<<"The quotient of the third pair is: " << quot(x[4],x[5]) <<endl;
system ("pause");
return EXIT_SUCCESS;
}
Are cin statements inside for loops not allowed in C++?
i guess you need to replace cin>>[ctr] with cin>>x[ctr].....this might fix your error.
For starters the function quot should be written like
float quot (int num1, int num2)
{
return static_cast<float>( num1 ) / num2;
}
Otherwise the return type float does not make a great sense because in this expression num1 / num2 there is used the integer arithmetic.
It is obvious that in this statement
cin>>[ctr];
there is a typo. You forgot to specify the array name x
cin >> x[ctr];
Also it will be better to subsritute this if statement
if(x[ctr]==0)
{
cout<<"Invalid number! Please enter a non-zero value: ";
cin>>x[ctr];
}
for a while statement like
while ( x[ctr] == 0 )
{
cout<<"Invalid number! Please enter a non-zero value: ";
cin>>x[ctr];
}
That's all you had to do.
Just change cin>>[ctr] to cin>>x[ctr]
It's on line 41. You need to specify the array name, x before the index [ctr]
Here's your code.
I recommend you to use a debugger to figure out such small human-made-errors yourself.
Also, read your code and try to visualize its flow before asking for solutions.
int main()
{
// ************************** TO DO **************************
// Place your code logic after this comment line
// ***********************************************************
int x[6];
cout<<"Enter 6 integers to divide: ";
for(int ctr=0; ctr<6; ctr++)
{
cin>>x[ctr];
if(x[ctr]==0)
{
cout<<"Invalid number! Please enter a non-zero value: ";
cin>>x[ctr];
}
}
cout<<"The quotient of the first pair is: " << quot(x[0],x[1]) <<endl;
cout<<"The quotient of the second pair is: " << quot(x[2],x[3]) <<endl;
cout<<"The quotient of the third pair is: " << quot(x[4],x[5]) <<endl;
system ("pause");
return EXIT_SUCCESS;
}

setprecision() not working as expected

I was doing a program which first takes 2 numbers (with float datatype) from the user and then ask the user about up-to what digit he want's to get the number divided and finally divides it up-to that number and 'cout<<' it. It compiled but din't worked up-to the mark when I calculated 22/7 which is an irrational no. up-to 100 digits it just calculated up-to 30 or 40 digits and then rest of was filled with zeros. Something like this:
3.1428570747375488281250000000000000000000000000000000000000000000000000000000000000000000000000000000
Here is my code:
#include <iostream>
#include <cstdlib>
#include <iomanip>
using namespace std;
int main()
{
system("clear");
float y;
int z;
float x;
float a;
cout << "\nHello User\n";
cout << "\nEnter first num to be divided: ";
cin >> x;
cout << "\nCool!! Now enter the 2nd number: \n";
cin >> y;
cout << "\Exelent!! Enter the place upto which u wanna caculate: ";
cin >> z;
a = x / y;
cout << fixed << showpoint;
cout << setprecision(z);
cout << "Calculating......\n" << a << endl;
return 0;
}
Floating point types have certain precision. You don't get exact results when operating on floats (or doubles). Now to get a better precision use double instead of float (See this post for more details).
You could #include <limits>, remove the step that gets the precision from input and change your code to:
std::cout << std::setprecision(std::numeric_limits<float>::max_digits10);
to display the result with maximum precision for the type you use.

Wrong answer displayed for simple math problems c++

I am just starting to learn C++ in college and our first assignment is to make a program that will do basic math. i feel like my code is not mistaken, but when i display the variable "sum", i get an answer that is way off. the value for the answer changes even if i input the same number multiple times. for example, i entered 2 for each variable and i got 1864273973 the first time and 1772335157 the second time. what could be causing this? i am using a macbook pro and code blocks, if anyone is wondering. i have also included my code.
#include <iostream>
#include <stdlib.h>
#include <math.h>
using namespace std;
int main()
{
//variabe declarations
int number, number2;
int sum, difference, product, dividend;
//calculations
sum = number + number2;
difference = number - number2;
product = number * number2;
dividend = number/number2;
//user inputs
cout << "\n1 of 2: Enter a number: ";
cin >> number;
cout << "\n2 of 2: Enter second number :";
cin >> number2;
cout << "\nNumber 1 entered: " << number << "\nNumber 2 entered: " << number2;
//output
cout << "\n" << number << "+" << number2 << "=" << sum << "\n";
}
C++ and almost every language nowadays use a structured system. It reads from top to bottom, so if you say "a = b+c" and then cin >> a, the calculation from b+c will be lost after the new input.
You are trying to calculate using variables that are declared but not initialized. In c++, this will cause the new variable to just receive "trash", a number you probably don't want. To correct this, I think you want to actually receive number and number2 BEFORE doing the math.

Is there a way to not include a negative number in an average, when entering a negative number is how you terminate the program?

Sorry about last time for those who saw my previous thread. It was riddled with careless errors and typos. This is my assignment:
"Write a program that will enable the user to enter a series of non-negative numbers via an input statement. At the end of the input process, the program will display: the number of odd numbers and their average; the number of even numbers and their average; the total number of numbers entered. Enable the input process to stop by entering a negative value. Make sure that the user is advised of this ending condition."
And here is my code:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int number, total1=0, total2=0, count1=0, count2=0;
do
{
cout << "Please enter a number. The program will add up the odd and even ones separately, and average them: ";
cin >> number;
if(number % 2 == 0)
{
count1++;
total1+=number;
}
else if (number >= 0)
{
count2++;
total2+=number;
}
}
while (number>=0);
int avg1 = total1/count1;
int avg2 = total2/count2;
cout << "The average of your odd numbers are: " << avg1 << endl;
cout << "The average of your even numbers are " << avg2 << endl;
}
It seems to be working fine, but when I enter a negative number to terminate the program, it includes it with the rest of the averaged numbers. Any advice to get around this? I know it's possible, but the idea escapes me.
Your main loop should be like this:
#include <iostream>
for (int n; std::cout << "Enter a number: " && std::cin >> n && n >= 0; )
{
// process n
}
Or, if you want to emit a diagnostic:
for (int n; ; )
{
std::cout << "Enter a number: ";
if (!(std::cin >> n)) { std::cout << "Goodbye!\n"; break; }
if (n < 0) { std::cout << "Non-positve number!\n"; break; }
// process n
}
After here:
cout << "Please enter a number. The program will add up the odd and even ones seperately, and average them: ";
cin >> number;
Immediately check if the number is negative
if(number < 0) break;
Now you wouldn't need to use your do-while loop in checking if the number is negative. Thus, you can use an infinite loop:
while(true) {
cout << "Please enter a number. The program will add up the odd and even ones seperately, and average them: ";
cin >> number;
if(number < 0) break;
// The rest of the code...
}
ADDITIONAL:
There is something wrong in your code. You aren't showing the user how much the number of even and odd numbers are, and the total number of numbers entered.
ANOTHER ADDITIONAL: You should use more meaningful variable names:
int totalNumEntered = 0, sumEven = 0, sumOdd = 0, numEven = 0, numOdd = 0;
Of course I am not limiting you to these names. You can also use other similar names.
FOR THE INTEGER DIVISION PROBLEM:
You must cast your expression values to the proper type (in this case, it is float). You should also change the averages variables' types to float:
float avg1 = float(total1) / float(count1);
float avg2 = float(total2) / float(count2);
Immediately after cin >> number, check for < 0, and break if so. Try to step through the program line by line to get a feel for the flow of execution. Have fun learning, and good luck!