Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
My current code is:
#include<iostream>
#include<cmath>
#include<cstdlib>
using namespace std;
int main()
{
char cAgain, type;
int x, y=0;
double addition(double num1, double num2), subtraction(double num1, double num2), division(double num1, double num2),
multiplication(double num1, double num2), exponential(double num1, double num2), num1, num2, total;
do
{
cout << "How many operations would you like to do?" << endl;
cin >> x;
if (x <= 0)
{
cout << "Error: You must have 1 or more operations." << endl;
}
else
{
while (x != 0, x--)
{
y++;
cout << "Enter in your "<<y<< " operation. (First Number (+,-,*,/,^) Second Number)" << endl;
cin >> num1 >> type >> num2;
switch (type)
{
case '+':
total = addition(num1, num2);
cout << num1 << " + " << num2 << "= " << total<< endl;
break;
case'-':
total = subtraction(num1, num2);
cout << num1 << " - " << num2 << "= " << total<< endl;
break;
case'/':
total = division(num1, num2);
cout << num1 << " / " << num2 << "= " << total<< endl;
break;
case'*':
total = multiplication(num1, num2);
cout << num1 << " * " << num2 << "= " << total << endl;
break;
case'^':
total = exponential(num1, num2);
cout << num1 << " ^ " << num2 << "= " << total << endl;
break;
}
}
}
cout << "Would you like to run the program again.(Y/N)" << endl;
cin >> cAgain;
} while (cAgain == 'Y' || cAgain == 'y');
return 0;
}
double addition(double num1, double num2)
{
double total;
total = num1 + num2;
return (total);
}
double subtraction(double num1, double num2)
{
double total;
total = num1 - num2;
return (total);
}
double division(double num1, double num2)
{
double total;
total = num1 / num2;
return (total);
}
double multiplication(double num1, double num2)
{
double total;
total = num1 * num2;
return (total);
}
double exponential(double num1, double num2)
{
double total;
total = pow(num1,num2);
return (total);
}
Currently the code works as it is suppose too.
It starts by asking
How many operations would you like to do?
You enter a number say 3
Then it ask you to enter in your operation
5+5
10
Then it ask for second
10^2
100
Then it ask for third
100-10
90
Then it ask if you want to start over and run the program again.
What I am trying to change it too is to 5+5^2-10= and it give me 20.
Essentially I want the user to be able to enter in the entire operation like 5+5^2-10= and it give me the correct answer. Allowing the user to type in a function and use '=' and return to start the calculation.
You can use following technique to solve an expression :
#include<iostream>
#include<cmath>
#include<stdio.h>
#include<cstdlib>
#include<map>
#include<stack>
using namespace std;
int expression_value(string str)
{
map<char,int>priority;
priority['^']=3;
priority['*']=2,priority['/']=2;
priority['+']=1,priority['-']=1;
stack<char>op_stack;
stack<int>val_stack;
int val=0;
for(int i=0;str[i];i++)
{
if(str[i]>='0'&&str[i]<='9')
val=val*10+str[i]-'0';
else
{
if(op_stack.empty()) // first operator
{
val_stack.push(val);
op_stack.push(str[i]);
}
else if(priority[op_stack.top()] < priority[str[i]]) // current operator is more prior then previous operator. so push it to stack.
{
val_stack.push(val);
op_stack.push(str[i]);
}
else // current operator is less prior then previous operator. so calculate previous operators resultant value
{
int num1,num2;
num1=val_stack.top(); val_stack.pop();
num2=val;
if(op_stack.top()=='+')
//val_stack.push(addition(num1, num2));
val_stack.push(num1 + num2);
else if(op_stack.top()=='-')
//val_stack.push(subtraction(num1, num2));
val_stack.push(num1 - num2);
else if(op_stack.top()=='*')
//val_stack.push(multiplication(num1, num2));
val_stack.push(num1 * num2);
else if(op_stack.top()=='/')
//val_stack.push(division(num1, num2));
val_stack.push(num1 / num2);
else
//val_stack.push(exponential(num1, num2));
val_stack.push(pow(num1 , num2));
op_stack.pop(); // as operator's value calculation done, pop it from the stack
op_stack.push(str[i]); // push the new operator
}
val=0;
}
}
val_stack.push(val); // last value
// calculate remaining operators value
while(!op_stack.empty())
{
int num1,num2;
num2=val_stack.top(); val_stack.pop();
num1=val_stack.top(); val_stack.pop();
if(op_stack.top()=='+')
//val_stack.push(addition(num1, num2));
val_stack.push(num1 + num2);
else if(op_stack.top()=='-')
//val_stack.push(subtraction(num1, num2));
val_stack.push(num1 - num2);
else if(op_stack.top()=='*')
//val_stack.push(multiplication(num1, num2));
val_stack.push(num1 * num2);
else if(op_stack.top()=='/')
//val_stack.push(division(num1, num2));
val_stack.push(num1 / num2);
else
//val_stack.push(exponential(num1, num2));
val_stack.push(pow(num1 , num2));
op_stack.pop();
}
return val_stack.top();
}
Here you have to pass the whole expression as string.
Operators will be stored in op_stack and value in val_stack
You should implement a
binary expression tree
I have just modify your program to meet your requirement:
#include <iostream>
#include <cstdio>
using namespace std;
char op;
double multiplication()
{
double product;
cin>>product;
while(1)
{
cin>>op;
if(op == '*')
{
double temp;
cin>>temp;
product *= temp;
}
else if(op == '/')
{
double temp;
cin>>temp;
product /= temp;
}
else break;
}
return product;
}
double addition()
{
double sum = multiplication();
while(op != '=')
{
if(op == '+')
sum += multiplication();
else if(op == '-')
sum -= multiplication();
else
{
cout<<"Operator error"<<endl;
return 0.0;
}
}
return sum;
}
int main()
{
char cAgain;
int x;
do
{
cout << "How many operations would you like to do?" << endl;
cin >> x;
if (x <= 0)
{
cout << "Error: You must have 1 or more operations." << endl;
}
else
{
while (x != 0, x--)
{
double result = addition();
cout<<result<<endl;
}
}
cout << "Would you like to run the program again.(Y/N)" << endl;
cin >> cAgain;
} while (cAgain == 'Y' || cAgain == 'y');
return 0;
}
Calculate some expressions like a+b,a-b,a^b,a*b etc is simple. But if you want to solve expressions like this:5+5^2-10,I think you need to learn something about Reverse Polish notation . It is not very difficult . Good Luck.
Related
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 1 year ago.
Improve this question
I am a college student looking for help on picking up the messy bits in this code I've worked on for class. I believe there's an error in this code that CodeBlocks is finicky with.
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
void func1();
void func2();
int main()
{
int num1, num2;
double num3;
int choice;
cout << fixed << showpoint << setprecision(2);
do
{
func1();
cin >> choice;
cout << endl;
if (choice == 1)
{
func2(num1, num2, num3);
cout << num1 << ", " << num2 << ", " << num3 << endl;
}
}
while (choice != 99);
return 0;
}
void func1()
{
cout << "To run the program, enter 1." << endl;
cout << "To exit the program, enter 99." << endl;
cout << "Enter 1 or 99: ";
}
void func2(int num1, int num2, double num3)
{
cout << "input 2 bumners a and b";
cin >> num1;
cin >> num2;
if (num1 >= num2){
num3 = pow(num1, num2);
}
else if (num1 < num2){
num3 = pow(num2, num1);
}
else if (num1 != 0 && num2 == 0){
num3 = sqrt(abs(num1));
}
else if (num2 != 0 && num1 == 0){
num3 = sqrt(abs(num2));
}
else if (num1 == 0 && num2 == 0){
num3 = 0;
}
}
Your func2() accepts parameters by value; whatever you do to those parameters is not visible outside of that function (when it returns). You should pass by reference.
void func2(int& num1, int& num2, double& num3)
This code isn't too hard to debug. I just tried compiling it, and I was told the error existed at line 6. Here's what you have to do:
Make sure you put in the correct parameters when you declare void func2() at line 6. It should have these parameters: (int num1, int num2, double num3).
The parameters must be the same when you declare the function and when you define the function, otherwise the defined function is never declared.
Write a function GetVolume() with 3 overloads. If one value is passed in, find the volume of a sphere with that value being its radius. If two values are passed in, find the volume of a cylinder with those values being its radius and height. If three values are passed in, find the volume of a box with the three values being its length, width, and height.
#include <iostream>
#include <cmath>
using namespace std;
double PI = 3.14;
double GetVolume(double r)
{
cout << "Sphere's volume is: ";
return ((4 * PI * pow (r , 3.0))/3);
}
double GetVolume(double r, double h)
{
cout << "Cylinder's volume is: ";
return (PI * pow (r, 2) * h);
}
double GetVolume(double l, double h, double w)
{
cout << "Box's volume is: ";
return (w * l * h);
}
int main()
{
double num = 0, num1 = 0, num2 = 0, num3 = 0;
double ans1, ans2, ans3;
cout << "Please enter 1, 2, or 3 numbers depending on whether you want the volume of a sphere, cylinder, or a box." << endl;
cin >> num1, num2, num3;
ans1 = GetVolume(num1);
ans2 = GetVolume(num1, num2);
ans3 = GetVolume(num1, num2, num3);
cout << ans1 << ans2 << ans3 << endl;
system("pause");
return 0;
}
I can't figure out why I cannot use my getvolume function to show three different results based on the numbers inserted in at the cin, I've attached at the top the question that I have to answer as to its part three of the five-part assignment. Sorry if this isn't enough information, I will try to provide more as best as I can.
You are only reading one number from standard input in this line
cin >> num1, num2, num3;
The commas here are operator,, which evaluates multiple expressions and discards all but the last. If you want to read multiple numbers, you need to chain >>
cin >> num1 >> num2 >> num3;
However it looks like you want to know how many numbers were entered, which you can test by looking at the value returned by operator>>.
if (!(cin >> num1)) {
cout << "no numbers entered";
} else if (!(cin >> num2)) {
cout << GetVolume(num1);
} else if (!(cin >> num3)) {
cout << GetVolume(num1, num2);
} else {
cout << GetVolume(num1, num2, num3);
}
You might want to read about the comma operator in c++.
https://en.cppreference.com/w/cpp/language/operator_other
Basically in the line,
num = GetVolume(num1), GetVolume(num1,num2), GetVolume(num1, num2, num3);
GetVolume(num1) gets evaluated. The result then gets discarded.
Then GetVolume(num1,num2) is evaluated. The result, discarded
Finally GetVolume(num1, num2, num3) gets evaluated, and its results is returned by the (Expr, Expr, Expr) on the RHS of operator =.
This returned value is then assigned to num. Which is why you only see one answer.
Similarly, your cin >> num1, num2, num3; Will only take one input i.e. num3.
Possible Fix
int ans1, ans2, ans3;
cin >> num1 >> num2 >> num3;
ans1 = GetVolume(num1);
ans2 = GetVolume(num1, num2);
ans3 = GetVolume(num1, num2, num3);
Other Issues
You return a type double from your functions but store them in int. This is had significant precision loss. I believe you wanted to store a double instead.
Your cout and following code seem incoherent. Perhaps you wish you take a single input first. Test whether it is 1,2 or 3. Then act accordingly.
you can declare class and overload GetVolume function like below
double PI = 3.14;
class calculateVolume {
public:
double GetVolume(double r)
{
cout << "Sphere's volume is: ";
return ((4 * PI * pow (r , 3.0))/3);
}
double GetVolume(double r, double h)
{
cout << "Cylinder's volume is: ";
return (PI * pow (r, 2) * h);
}
double GetVolume(double l, double h, double w)
{
cout << "Box's volume is: ";
return (w * l * h);
}
}
int main() {
calculateVolume volObject;
cout<<volObject.GetVolume(5);
return 0;
}
above code will give output Sphere's volume is: 523.333
It is just working snippet you can adjust code according to your need
Expanding on the answer by Caleth, if OP's issue (apart from the comma operator) is how to select a particular function based on how many numbers the user inputs, we may read an entire line from the input stream with std::getline and then, using a std::stringstream, extract a number at a time.
using std::cout;
cout << "Please enter 1, 2, or 3 numbers depending on whether you want"
"the volume of a sphere, cylinder, or a box.\n";
std::string line;
while ( std::getline(std::cin, line) )
{
if (line.empty())
continue;
std::istringstream ss {line};
double num_1, num_2, num_3;
if ( !(ss >> num_1) )
{
cout << "No number in input.\n";
continue;
}
else if ( !(ss >> num_2) )
{
cout << "Sphere's volume is: " << GetVolume(num_1) << '\n';
}
else if ( !(ss >> num_3) )
{
cout << "Cylinder's volume is: " << GetVolume(num_1, num_2) << '\n';
}
else // Other numbers in the line will be ignored.
{
cout << "Box's volume is: " << GetVolume(num_1, num_2, num_3) << '\n';
}
}
Live example HERE.
I'm trying to code a postfix calculator, but I keep running into two issues-
first: When the calculator encounters a space, it sort of just exits immediately
second: when it encounters a non operator/non digit (ie- z) it doesn't display the error message that I coded.
int main()
{
stack <int> calcStack;
string exp;
char ans;
cout << "\nDo you want to use the calculator?" << endl;
cin >> ans;
while (ans == 'y')
{
cout << "\nEnter your exp" << endl;
cin >> exp;
for (int i = 0; i < exp.size(); i++)
{
if (isspace(exp[i]))
{
}
else if (isdigit(exp[i]))
{
int num = exp[i] - '0';
calcStack.push(num);
}
else
doOp(exp[i], calcStack);
}
while (!calcStack.empty())
{
calcStack.pop();
}
cout << "\nDo you want to use the calculator again?" << endl;
cin >> ans;
}
system("pause");
return 0;
}
This is the function--
void doOp(const char & e, stack <int>& myS)
{
if (myS.size() == 2)
{
int num1, num2, answ;
num2 = myS.top();
myS.pop();
num1 = myS.top();
myS.pop();
if (e == '+')
answ = num1 + num2;
else if (e == '-')
answ = num1 - num2;
else if (e == '*')
answ = num1 * num2;
else if (e == '/')
answ = num1 / num2;
else if (e == '%')
answ = num1 % num2;
else
cout << "\nError- Invalid operator" << endl;
cout << "\nCalculating..." << endl << answ << endl;
myS.push(answ);
}
else
cout << "\nInvalid stack size- too few, or too many" << endl;
}
In your main loop, you're reading strings with the string extractor:
cin >> exp;
THe string extractor is space sensitive. So as soon as a space char is encountered in the input, the string reading stops, and the witespace is not included in exp.
If you want to get a full line including spaces, you should opt for:
getline (cin, exp);
Edit:
The issue you experience with getline() is realted to the char extraction when you ask if user wants to use the calculator. Entering y is not sufficient. So you'l enter yenter. Only the y will be put into ans, so that getline() will start reading an empty line.
To solve this, update your initial input:
cin >> ans; // as before
cin.ignore (INT_MAX, '\n'); // add this to skip everything until newline included
Here an online demo showing that it works (including error message in case of wrong operator)
#include "stdafx.h"
#include <iostream>
#include <stdexcept>
using namespace std;
inline double multplication(double num1, double num2);
inline double division(double num1, double num2);
inline double addition(double num1, double num2);
inline double substraction(double num1, double num2);
int main()
{
cout << "Welcome to 'The calculator' just enter a number the operator '*, /, + and -' then the second number enjoy" << endl;
char redo = 'r'; double result = 0; int cnt = 0;
while (redo == 'r' || redo == 'R')
{
try
{
if (cnt > 0)
cout << "Ok same rules as before" << endl;
int num1 = 0, num2 = 0; char inputedOperator = '*';
cin >> num1 >> inputedOperator >> num2;
switch (inputedOperator)
{
case('*') :
result = multplication(num1, num2);
break;
case('/') :
result = division(num1, num2);
break;
case('+') :
result = addition(num1, num2);
break;
case('-') :
result = substraction(num1, num2);
break;
default:
throw runtime_error("Invalid operator");
}
}
catch (runtime_error err)
{
cout << err.what() << endl;
cout << "Enter y to redo or anykey to exit" << endl;
cin >> redo;
++cnt;
continue;
}
cout << "The answer is " << result << "\nPlease enter y to redo or anykey to exit" << endl;
cin >> redo;
++cnt;
}
cout << "Thanks for using" << endl;
return 0;
}
inline double multplication(double num1, double num2)
{
return num1 * num2;
}
inline double division(double num1, double num2)
{
return num1 / num2;
}
inline double addition(double num1, double num2)
{
return num1 + num2;
}
inline double substraction(double num1, double num2)
{
return num1 - num2;
}
Whenever I run '3 * 2' as the input it works fine but for '3 * d' it keeps looping at the end of my code also '3 d 3' is fine since it just sais invalid operator. So my question is why does it keep looping and how do I fix it?
added
if (cin.fail())
{
cin.clear();
cin.ignore(numeric_limits<int>::max(), '\n');
}
To clear the invalid input and buffer. Found info on cplusplus.com/forum/beginner/2957/
I was trying to make a program in c++ that should order 3 random numbers (the user will write them) and then print which is the higher and the lower, but if two numbers or more are equal should print it.
New code:
#include <iostream>
using namespace std;
int main()
{
int num1;
int num2;
int num3;
cout << "num1" << endl;
cin >> num1;
cout << "num2" << endl;
cin >> num2;
cout << "num3" << endl;
cin >> num3;
if(num1 == num2 && num3==num2 && num1==num3){
cout << "all numbers are equal";
}
else if (num1 == num2){
cout << "num1 and num2 are equal";
}
else if (num2 == num3){
cout << "num2 and num3 are equal";
}
else if(num3 == num1){
cout << "num1 and num3 are equal";
}
else{
if (num1 != num2 && num2 != num3 && num3 != num1){
if (num1 > num2 && num1 > num3){
cout << "higher is num1";
}
else if(num2 > num1 && num2 > num3){
cout << "higher is num2";
}
else if(num3 > num1 && num3 > num2){
cout << "higher is num3";
}
}
}
return 0;
}
New problem:
The programm needs to know which is the lowest too, so how can I do that?
Old code:
#include <iostream>
using namespace std;
int main()
{
int num1;
int num2;
int num3;
cout << "num1" << endl;
cin >> num1;
cout << "num2" << endl;
cin >> num2;
cout << "num3" << endl;
cin >> num3;
if(num1 == num2 && num3==num2 && num1==num3){
cout << "all your numbers are equal";
}
if (num1 != num2 && num2 != num3 && num3 != num1){
if (num1 > num2 && num1 > num3){
cout << "num1";
}
else if(num2 > num1 && num2 > num3){
cout << "num2";
}
else /*(num3 > num1 && num3 > num2)*/{//Here I tried to use and else if
cout << "num3";
}
}
return 0;
}
Old problem
This code is all wrong, but I don't know what I'm doing wrong, please help me.
And I have a last question, do I have a limit of if's into a if sentence? or I just can't write two else if or..? Thanks.
#include <iostream>
#include <set>
int main()
{
std::set<int> numbers;
int input;
for (int i=1; i<=3; ++i) {
std::cout << "Enter number " << i << ": ";
std::cin >> input;
numbers.insert(input);
}
if (numbers.size() < 3) {
std::cout << "You entered the same number more than once, silly!" << std::endl;
std::cout << "Nevertheless, ";
}
std::cout << "the maximum number is " << *numbers.rbegin() << std::endl;
}
The important feature of this code is that it takes advantage of the properties of std::set which are:
It keeps all its elements in sorted order
It does not allow duplicate elements
std::set::rbegin is used to get the last element, which is the largest number (because the numbers are automatically sorted).
This code does not display which numbers are the largest and smallest, but this can easily be added. For example, std::set::insert returns information that can allow you to determine which insertion failed in the set. An std::set can contain only single copies of its contained objects. Therefore, if the user enters a number more than once the calls to insert will fail.
The following piece of code solves your purpose. It has three functions findLargest, findSmallest and checkEqual. This is a very basic program and can be modified to your needs on how to display and what to return etc etc.
#include <iostream>
using namespace std;
void findLargest(int n1,int n2,int n3)
{
if(n1>n2 && n1>n3)
{
cout<<"Largest number is :"<<n1;
cout<<"\n";
}
else if((n2>n1) && (n2>n3))
{
cout<<"Largest number is :"<<n2;
cout<<"\n";
}
else
{
cout<<"Largest number is :"<<n3;
cout<<"\n";
}
}
void findSmallest(int n1,int n2,int n3)
{
if(n1<=n2 && n1<=n3)
{
cout<<"Smallest number is :"<<n1;
cout<<"\n";
}
else if((n2<=n1) && (n2<=n3))
{
cout<<"Smallest number is :"<<n2;
cout<<"\n";
}
else
{
cout<<"Smallest number is :"<<n3;
cout<<"\n";
}
}
int checkEqual(int n1,int n2,int n3)
{
if(n1==n2 && n2==n3 && n3==n1)
{
cout<<"All three are equal";
cout<<"\n";
}
else if(n1==n2||n2==n3||n3==n1)
{
cout<<"Two numbers are equal";
cout<<"\n";
}
else
{
cout<<"None are equal.. Finding Largest and Smallest....!!";
cout<<"\n";
}
}
int main() {
int num1,num2,num3;
cout<<"Enter the numbers";
cin>>num1>>num2>>num3;
cout<<"\n";
checkEqual(num1,num2,num3);
findSmallest(num1,num2,num3);
findLargest(num1,num2,num3);
return 0;
}
Ideone link: http://ideone.com/hz4keQ
Hope it helps. :)