C++ Basic Calculator - c++

I'm new to C++ and programming in General. I was assigned to make a calculator for my C++ class and this is what I have so far.
#include <iostream>;
#include <iomanip>;
using namespace std;
int main() {
double x,y;
char op;
cout << "Enter Expression:";
cin >> x >> op >> y;
if (op = '+')
{
cout << "Result:" << x + y << endl;
}
else if (op = '-') {
cout << "Result:" << x - y << endl;
}
else if (op = '*') {
cout << "Result:" << x*y << endl;
}
else if (op = '/') {
cout << "Result:" << x / y << endl;
}
else if (op = '%') {
cout << "Result:" << x % y << endl; // <--- line 23
}
else {
return 0;
}
}
The x and y variables on line 23 both have errors saying that the expression must have an integral or unscoped enum type and I don't understand why.

The % operation is defined only for integer values. You cannot apply it for doubles. Also you have a typical novice mistake: In C++ operator = is assignment operator a = b mean get b value and put it in a. But operator == is comparison operator, a == b mean if a equally b return true. If you want to compare values use ==, not =.

With floating point division there is no remainder. What should be the result of 2.5 % 1.2?
You could use ints for that case:
else if (op == '%') {
cout << "Result:" << (int)x % (int)y << endl;
}
but note that when the user types 2.5 % 1.2 this will show the result for 2 % 1.
PS: Also note that you have = (assignment) in the conditions when it should be == (comparison).

You are using % for double, it is only for integers.
If you want to use same functionality for double. you can use fmod()
double z = fmod(x,y);
You should modify your code to below
#include <iostream>;
#include <iomanip>;
using namespace std;
int main() {
double x,y;
char op;
cout << "Enter Expression:";
cin >> x >> op >> y;
if (op == '+')
{
cout << "Result:" << x + y << endl;
}
else if (op == '-') {
cout << "Result:" << x - y << endl;
}
else if (op == '*') {
cout << "Result:" << x*y << endl;
}
else if (op == '/') {
cout << "Result:" << x / y << endl;
}
else if (op == '%') {
cout << "Result:" << fmode(x,y) << endl;
}
else{
return 0;
}
}

The remainder operator % does not work for operands of type double (cf., for example, cppreference.com/Multiplicative operators):
For the built-in operator %, lhs and rhs must both have integral or
unscoped enumeration type
You could write static_cast<int>(x)%static_cast<int>(y) instead.
Further, note that = is assignment operator; for comparisons (as in your case with if (op = '%')), use equality operator ==, i.e. if (op == '%').

Related

My simple c++ calculator is not working as it should be [duplicate]

This question already has answers here:
How to compare multiple strings inside an if statement?
(6 answers)
Closed 3 years ago.
This is a suppposed to be simple calculator which can plus, minus, mulyiply or divide two numbers that are input into the console (int a, b).
The problem is probably with my if / else statemnts. Even though I input "Minus" , "Multiply" or "Divide" into the console, the operator (std::string operator) is always set to "plus", thus adding the two numbers even though that was not my desired operator.
Ive tried removing the [int plus();] function alltogether to see the result, then the default and fixed operator changed to minus.
#include <iostream>
// the problem is probably at [void core();]
std::string operation;
int a;
int b;
class common {
public:
void print() {
std::cout << "a: ";
std::cin >> a;
std::cout << "b: ";
std::cin >> b;
}
};
int plus() {
common plus1;
plus1.print();
int ans = a + b;
std::cout << "ANS: " << ans << "\n";
return a + b;
}
int minus() {
common minus1;
minus1.print();
int ans = a - b;
std::cout << "ANS: " << ans << "\n";
return a - b;
}
int multiply() {
common multiply1;
multiply1.print();
int ans = a * b;
std::cout << "ANS: " << ans << "\n";
return a * b;
}
int divide() {
common divide1;
divide1.print();
int ans = a / b;
std::cout << "ANS: " << ans << "\n";
return a / b;
}
void core() {
std::cout << "\nplus / minus / multiply / divide\n"
<< "operation: ";
std::cin >> operation;
if (operation == "plus" or "Plus") {
plus();
}
else if (operation == "minus" or "Minus") {
minus();
}
else if (operation == "multiply" or "Multiply") {
multiply();
}
else if (operation == "divide" or "Divide") {
divide();
}
else {
std::cout << "Invalid Operation!\n";
}
}
int main() {
for (int i = 0; i < 99; i++) {
core();
}
}
When i set [std::string operation] as "multiply" through
[std::cin >> operation], i expected the [multiply();]
function to be called but instead, [plus();] function is called no matter what operator i set.
Your if statements are wrong. You have
if (operation == "plus" or "Plus") {
You want:
if (operation == "plus" or operation == "Plus") {
Same for the others.
The or "Plus" part of the above is always true, since "Plus" is treated as a pointer when on its own and if that pointer is not nullptr (which it is not), then it evaluates to true in a boolean context.
The condition operation == "plus" or "Plus" is always true, because "Plus" is implicitly cast to true.
Setting aside some bad practice, what you want is operation == "plus" || operation == "Plus".

C++ Newbie questions

My task:
Write the following program: The user is asked to enter 2 floating point numbers (use doubles). The user is then asked to enter one of the following mathematical symbols: +, -, *, or /. The program computes the answer on the two numbers the user entered and prints the results. If the user enters an invalid symbol, the program should print nothing.
My code:
#include <iostream>
using namespace std;
int introducir()
{
int a;
cin >> a;
return a;
}
bool simbolo(char x)
{
if (x == '+')
return true;
if (x == '-')
return true;
if (x == '*')
return true;
if (x == '/')
return true;
return false;
}
void operar(char x, int a, int b)
{
if (x == '+')
cout << a+b;
if (x == '-')
cout << a-b;
if (x == '*')
cout << a*b;
if (x == '/')
cout << a/b;
else cout << "INVALID OPERATION SIMBOL";
}
int main()
{
cout << "insert 2 numbers"<< endl;
int a =introducir();
int b= introducir();
cout << "introduce one of these simbols : +,-,* o /." << endl;
char x;
cin >> x;
bool primo= simbolo(x);
{
if (primo) {
cout << "simbol is valid" << endl;
} else {
cout << "invalid simbol" << endl;
}
cout << "operation result is:";
}
operar(x,a,b);
}
If the symbol is not in (+,-,*,/), I want it to return a message "INVALID OPERATION SIMBOL"; however it returns it even if the symbols are valid. How do I fix that?
The way you've written it, the else only applies to the final if.
Change to
if (x == '+'){
cout << a+b;
} else if (x == '-'){
cout << a-b;
} else if (x == '*'){
cout << a*b;
} else if (x == '/'){
cout << a/b;
} else {
cout << "INVALID OPERATION SIMBOL";
}
and similar for the other if statements. (You could even consider refactoring to a switch block.) The braces are not entirely necessary but I've put them in for clarity.

Having trouble with a 'while' loop in C++

I started building a very simple version of a calculator in C++. The idea is to perform basic operations with only two numbers and then loop back so the user can make a new calculation.
The program looks like this:
#include<iostream>
#include<string>
#include"mathOperations.h"
using namespace std;
int main()
{
int x, y;
string operation;
string repeat = "y";
while (repeat == "y" or "Y")
{
cout << "Welcome! This is a raw version of a calculator - only use two numbers." << endl;
cin >> x >> operation >> y;
if (operation == "+")
{
cout << "Result: " << add(x, y) << endl;
}
else if (operation == "-")
{
cout << "Result: " << subtract(x, y) << endl;
}
else if (operation == "*")
{
cout << "Result: " << multiply(x, y) << endl;
}
else if (operation == "/")
{
cout << "Result: " << divide(x, y) << endl;
}
else
{
cout << "This is not a valid sign. Please choose another one!" << endl;
}
cout << "Wanna go again? Type 'y' or 'n'." << endl;
cin >> repeat;
if (repeat == "n" or "N")
{
cout << "Alright, have a nice day!" << endl;
break;
}
}
}
int add(int x, int y)
{
return x + y;
}
int subtract(int x, int y)
{
return x - y;
}
int multiply(int x, int y)
{
return x * y;
}
int divide(int x, int y)
{
return x / y;
}
NOTE: There is a 'mathOperations.h' file in which I have made forward declarations of all functions used.
The problem is that whenever I type in 'y' to make it loop, it simply outputs the following 'if' statement and breaks out of the loop and the program finishes. I couldn't quite figure out why this is happening, since the 'if' statement is only supposed to run if I type in 'n'.
repeat == "n" or "N"
evaluates to
(repeat == "n") || "N"
see the C++ operator precedence.
The first repeat == "n" evaluates to true or false depending on your input, but the second clause of the OR, i.e. "N", always evaluates to true because it is a string literal that decays to a non-zero const char* pointer, and in C or C++ everything non-zero is implicitly converted to true. So your OR clause is always true, which implies that the if block will always be executed.
As mentioned in the comments, you need to do
if(repeat == "n" || repeat == "N") {...}
Similarly with the first while condition.
Nice code! I try using "||" in place of your "or" in your if statements. Might want to refresh your knowledge with C++ short-circuiting of booleans.

C++ calling different methods if char is entered

Hello I'm trying to create a console application that allows the user to input a single character to preform an arithmetic operation.
Currently the program only adds the two numbers together even if I input an m, meaning multiply. I believe it is going straight into the first if statement for some reason even if I dont want addition.
#include <iostream>
using namespace std;
int add(int a, int b)
{
int c;
c = a + b;
return c;
}
int subtract(int a, int b)
{
int c;
c = a - b;
return c;
}
int multiply(int a, int b)
{
int c;
c = a * b;
return c;
}
int divide(int a, int b)
{
int c;
c = a / b;
return c;
}
int remainder(int a, int b)
{
int c;
c = a % b;
return c;
}
int main ()
{
int a;
int b;
char op;
cout << "****************Integer Calculator**************** " << endl << "Press enter to continue." << endl;
cout << "Enter the first integer: " << endl;
cin >> a;
cout << "Enter the second integer: " << endl;
cin >> b;
cout << "What operation would you like to perform? Enter a single character " << endl << "Add - A , a or + " << endl <<
"Subtract - S , s or - " << endl << "Multiply - M , m or * " << endl << "Divide - D , d or / " << endl << "Remainder - R , r or % " << endl;
cin >> op;
if (op ='A' || 'a' || '+')
{
int answer1 = 0;
answer1 = add(a, b);
cout << "The answer is: " << answer1 << endl;
system("PAUSE");
return 0;
}
else if(op == 'S' || 's' || '-')
{
int answer2 = 0;
answer2 = subtract(a, b);
cout << "The answer is: " << answer2 << endl;
system("PAUSE");
return 0;
}
else if (op == 'M' || 'm' || '*')
{
int answer3 = 0;
answer3 = multiply(a, b);
cout << "The answer is: " << answer3 << endl;
system("PAUSE");
return 0;
}
else if (op == 'D' || 'd' || '/')
{
int answer4 = 0;
answer4 = divide(a, b);
cout << "The answer is: " << answer4 << endl;
system("PAUSE");
return 0;
}
else if (op == 'R' || 'r' || '%')
{
int answer5 = 0;
answer5 = remainder(a, b);
cout << "The answer is: " << answer5 << endl;
system("PAUSE");
return 0;
}
Your logic is incorrect, and you are using the assignment operator to boot.
if (op ='A' || 'a' || '+')
This should be:
if (op == 'A' || op == 'a' || op == '+')
Usually for stuff like this we use a switch:
switch( toupper(op) )
{
case 'A':
case '+':
// Do adding...
break;
case 'S':
case '-':
// Do subtraction...
break;
// etc...
default:
cout << "Unknown operation : " << op << endl;
}
In your if statement
(op ='A' || 'a' || '+')
you are not testing if op equals 'A'. You are setting op equal to 'A', and then testing if 'a' and '+' are true, which they are. To fix this, use the == operator, and test op for every case like so:
if (op == 'A' || op == 'a' || op == '+')...
else if(op == 'S' || op == 's' || op == '-')...
// and so on

C++ Calculator always returns 7208640

This is the code for my calculator:
#include <iostream>
using namespace std;
int main()
{
int fNumber, sNumber, sum;
string op;
cout << "You will be asked for two numbers and the operator to use on them.\nCurrently supported operators are:\n";
cout << " Addition: +\n Subtraction: -\n Multiplication: *\n Division: \\\n Modulo: %\n\n";
cout << "First Number: ";
cin >> fNumber;
cout << "\nSecond Number: ";
cin >> sNumber;
cout << "\nOperator: ";
cin >> op;
if(op == "+"){
int sum = fNumber + sNumber;
} else if(op == "x" || op == "*"){
int sum = fNumber * sNumber;
} else if(op == "/"){
int sum = fNumber / sNumber;
} else if(op == "-"){
int sum = fNumber - sNumber;
} else if(op == "%"){
int sum = fNumber % sNumber;
} else{
cout << "\nPlease use a correct Operator\n";
return 1;
}
cout << "\n" << fNumber << " " << op << " " << sNumber << " = " << sum << "\n";
return 0;
}
I have absolutely no idea why, but for some reason, whatever numbers or operators I give it it returns "7208640" as the answer:
You will be asked for two numbers and the operator to use on them.
Currently supported operators are:
Addition: +
Subtraction: -
Multiplication: *
Division: \
Modulo: %
First Number: 6
Second Number: 2
Operator: /
6 / 2 = 7208640
Process returned 0 (0x0) execution time : 4.612 s Press any key to
continue.
if(op == "+"){
int sum = fNumber + sNumber;
should be
if(op == "+"){
sum = fNumber + sNumber;
and the same for all the other int sum except the first. You declare a variable once, not every time you use it.
As above, remove the int declarations from inside the if statements.
Also, please change the name of the sum variable to something like "answer." A result from subtraction, multiplication, division and modulo is referred to as difference, product, quotient, and remainder, respectively.