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.
Related
I have this problem, I would like to display that if 0/0, Output is that : "Cannot divide 0 by itself". How can I tweak my code so that I can display that output? If so, what code should I be using in order to make my goal come into fruition?
Here's my code below:
#include <iostream>
using namespace std;
double isAdd(double x, double y);
double isSub(double x, double y);
double isMult(double x, double y);
double isDiv(double x, double y);
int main() {
cout << "Calculator\n";
double oneV, twoV;
char choice = 'a';
cout << "Enter 2 Values : \n";
cin >> oneV;
cin >> twoV;
cout << "Enter Operation to Use: ( a / s / m / d) \n";
cout << "a = addition, s = subtraction, m = multiply, d = divide\n";
cin >> choice;
if (choice == 'a') {
cout << "The Sum is : " << isAdd(oneV, twoV);
}
if (choice == 's') {
cout << "The Difference is : " << isSub(oneV, twoV);
}
if (choice == 'm') {
cout << "The Product is " << isMult(oneV, twoV);
}
if (choice == 'd') {
cout << "The Quotient is " << isDiv(oneV, twoV);
}
}
double isAdd(double x, double y) {
double answer = x + y;
return answer;
}
double isSub(double x, double y) {
double answer = x - y;
return answer;
}
double isMult(double x, double y) {
double answer = x * y;
return answer;
}
double isDiv(double x, double y) {
double answer = x / y;
return answer;
}
if ('d' == choice) {
if (0 == twoV)
//cout << "Cannot divide 0 by itself\n";
cout << "Division by zero.\n";
else
cout << "The Quotient is " << isDiv(oneV, twoV);
}
Tips:
get rid of all of those ifs and use a switch.
Comparing to 0 will work in this case, but if you were working with a calculated value, you'd need to check for "nearly zero". See https://en.cppreference.com/w/cpp/types/numeric_limits/epsilon . This is due to floating point precision limitations.
If the user enters something other than a, s, m or d, your code silently exits. You should display something like "Invalid input."
You're also not taking into account input case: ie, A vs a.
if (choice == 'd')
{
if (twoV == 0)
{
//this one for cannot dividing 0
cout << "Undefined value (" << oneV << "/0)"<<endl;
}
else
{
//this one for normal other values
cout << "The Quotient is " << isDiv(oneV, twoV);
}
}
Tips:-
In here you use only conditional statements. But you can use switch case also. So, if you use them for implementing this it would be very attractive than using conditional statements. Refer them.
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 == '%').
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.
I am a student and I'm trying to write a function that returns "true" if I enter a vowel, and "false" if I enter a consonant.
This is what I wrote:
#include <iostream>
using namespace std;
int main()
{
bool isVowel(char x);
}
bool isVowel(char x)
{
cout << "Enter a letter" << endl;
cin >> x;
if (x == 'a', 'e', 'i', 'o', 'u')
return true;
else
return false;
}
I compiled with g++ isvowel.cpp -o isvowel, and apparently there were no errors, but then I tried to execute using ./isvowel and nothin happened.
What's wrong?
Your if equality comparison does not work. As Sam stated in the comments, you need to exlicitely compare x with each value.
bool isVowel(char x)
{
// The if is not really needed here since you can
// just return the result of the comparison
if (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u') {
return true;
}
else {
return false;
}
}
To call this method:
std::cout << "Input character" << std::endl;
char x;
std::cin >> x;
bool vowel = isVowel(x);
std::cout << "Is vowel: " << vowel << std::endl;
The comma doesn't work that way you think (it's been explained above), but the reason that nothing happens is because you don't really call the isVowel function. The code
bool isVowel(char x);
defines a new function that hides the one you meant to call. To make this work, you need to call the function correctly, i.e.
isVowel('x'); // or, better, isVowel(), as I'll explain below
and move the isVowel function definition above main, because otherwise it wouldn't be visible inside main. The third thing is, the "char x" parameter you pass to the function doesn't really do anything, since you overwrite it with cin >> x; You probably want to use a method that takes no parameters. And finally, if you want to see the result, you need to print it to the screen. So, to put this together, your code should look like:
#include <iostream>
using namespace std;
bool isVowel()
{
cout << "Enter a letter" << endl;
char x;
cin >> x;
if (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u')
return true;
else
return false;
}
int main()
{
bool b = isVowel();
cout << b << endl;
}
or, if you prefer,
#include <iostream>
using namespace std;
bool isVowel(char x)
{
if (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u')
return true;
else
return false;
}
int main()
{
cout << "Enter a letter" << endl;
char x;
cin >> x;
bool b = isVowel(x);
cout << b << endl;
}
I am new to C++ programming and haven't done anything in a week, so I was messing around with things I know thus far to see if I have to go over things again.
However, I ran into an issue with bools (haven't really used them before).
Source:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
signed long int x;
unsigned short int y = 12345;
bool POSX;
bool yes;
cin >> x;
if (x >= 0)
{
POSX = true;
}//end of if for bool
else
{
POSX = false;
}
cout << "This is the current value of X: " << x << endl;
if(x < y)
{
cout << "x is less than the integer y \n \n";
}//end of if
else
{
cout << "y is greater than the integer x \n \n";
}//end of else
cout << "The current value of Y is: " << y << endl << endl << endl;
cout << "Is X positive?: " << POSX << endl << endl;
cout << "How much more would X need to be to surpass y? The answer is: " << y - x << endl;
if(x > y)
{
cout << "well, actually, x is greater than y by: " << y - x << " so you would need to add that to get to the value of x" <<endl <<endl;
}//end of if
cout << "Do you like cookies? Enter below. . ." <<endl;
cin >> yes;
if(yes = "yes") // should this be if(yes = 1)?
{
cout << "I do too! But only when they are soft and gooey!";
} //end of if for bool yes
else
{
cout << "Well, join the dark side, and you may be persuaded by the power of cookies and the power of the dark forces!";
}//end of else for bool yes
char f;
cin >> f;
return 0;
} //end of main
The issue I have is when I try to compile, for one, the program exits before I can see the result of the cookie question [so I have to place a break point in the compiler], and second, when I can see the answer, it always comes up with the yes response, and not anything else.
So, if I put no as the input, it still outputs the if for the bool yes being true. I am not sure if I am defining the if clause correctly in the last statement.
Could anyone help?
Ok, two things. Your major problem is this:
if(yes = "yes")
'yes' is definend as a bool type, i.e., it can hold the values "true" or "false". You attempting to compare comparing (actually attempting to assign due to using only one = instead of ==, which is how you check for equality) a boolean to a string "yes". Well, that makes no sense. It should be:
if( yes )
That's it. 'yes' is already a boolean, and the expression in an if statement requires no more.
Secondly, constructs like this are redundant and unnecessary:
if (x >= 0)
{
POSX = true;
}//end of if for bool
else
{
POSX = false;
}
You are checking for a boolean value and then assigning one. Just do it in one line like this:
POSX = (x >=0 );
Also, you typically don't use all caps for local variables.
One more thing; you are entering string data ("no" or "yes") and cin is expecting an int. I suggest that you spend some time learning about what data types are.
The issue I have is when I try to compile, for one, the program exits before I can see the result of the cookie question
That's because you invalidated cin when you put "no" as the value. operator>>(std::istream&, bool&) assumes numeric input. Values not equal to zero will be interpreted as true, and values equal to zero will be interpreted as false.
If you supply input that cannot be parsed as numeric badbit will be set on the stream. Attempting to use the stream while it is in this failed condition will result in garbage being read (or rather, undefined behavior), and no advancement of the get pointer in the stream.
Change yes to a string(#include <string>), and then compare it like this:
if (yes == "yes")
There are a couple of things going wrong here, but I think the one tripping you up is cin >> yes; In C++, false is 0. Therefore, this will likely return true for any non-zero input values. A more reliable approach would be to ask for and evaluate on something else, for instance, character input:
cout << "Do you like cheese? (y/n) ";
char c;
cin >> c;
if ( c == 'y' || c == 'Y' )
do whatever;
Additionally, when testing conditionals, be sure to use "double-equals", condition == true. Better yet, adopt the shorthand where:
(condition) means (condition == true)
(! condition) means (condition == false)
Hope that gives you a start in the right direction.
Here is the edited sources code, I made changes so study it and compare with the original code. *e*
#include <iostream>
#include <string>
#include <iomanip> //headerfile for boolalpha
using namespace std;
int main()
{
string answer;
signed long int x;
unsigned short int y = 12345;
bool POSX;
bool yes;
cout<<"Enter any value: ";
cin >> x;
if (x >= 0)
{
cout << boolalpha; // print bools as true or false
POSX = true;
}//end of if for bool
else
{
cout << boolalpha; // print bools as true or false
POSX = false;
}
cout << "This is the current value of X: " << x << endl;
if(x < y)
{
cout << "x is less than the integer y \n \n";
}//end of if
else
{
cout << "y is greater than the integer x \n \n";
}//end of else
cout << "The current value of Y is: " << y << endl << endl << endl;
cout << "Is X positive?: " << POSX << endl << endl;
cout << "How much more would X need to be to surpass y? The answer is: " << y - x << endl;
if(x > y)
{
cout << "well, actually, x is greater than y by: " << y - x << " so you would need to add that to get to the value of x" <<endl <<endl;
}//end of if
cout << "Do you like cookies? Yes/No. . ." <<endl;
cin >> answer; //this is a string
if(answer =="yes") // it can be a simple if statement
{
cout << "I do too! But only when they are soft and gooey!";
} //end of simple if
else
{
cout << "Well, join the dark side, and you may be persuaded by the power of cookies and the power of the dark forces!";
}//end of else for simple if
return 0;
} //end of main`