Program output (Basic operators for c++). Order of operations? - c++

// H2.cpp : Tihs program runs different mathmatical operations on numbers given by the user
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int a;
cout << "Enter a number for a: "; //Prompts the user for a and b inputs
cin >> a;
int b;
cout << "Enter a number for b: ";
cin >> b;
cout << "A is " << a << "\tB is " << b << endl;
cout <<"Sum of a and b is equal to " << a << " + " << b << " and the result is " << (a + b) << endl; //Performs addition operator and gives output
cout <<"Product of a and b is equal to " << a << " * " << b << " and the result is " << (a * b) << endl;
cout <<"a > b is " << a << " > " << b << " and the result is " << (a > b) << endl;
cout <<"a < b is " << a << " > " << b << " and the result is " << (a < b) << endl;
cout <<"a == b is " << a << " == " << b << " and the result is " << (a == b) << endl; //Performs boolean operator and outputs result
cout <<"a >= b is " << a << " >= " << b << " and the result is " << (a >= b) << endl;
cout <<"a <= b is " << a << " <= " << b << " and the result is " << (a <= b) << endl;
cout <<"a != b is " << a << " != " << b << " and the result is " << (a != b) << endl;
cout <<"a -= b is " << a << " -= " << b << " and the result is a = " << (a -= b) << endl; //Performs - operator on a - b and makes a equal to the new result
cout <<"a /= b is " << a << " /= " << b << " and the result is a = " << (a /= b) << endl;
cout <<"a %= b is " << a << " %= " << b << " and the result is a = " << (a %= b) << endl; //Performs % operator on a % b and makes a equal to the new result. Ripple effect created from previous 2 lines as the value of a changes each time.
return 0;
The output I'm concerned with is here:
a -= b is -4198672 -= 4198672 and the result is a = -4198672
a /= b is -1 /= 4198672 and the result is a = -1
a %= b is -1 %= 4198672 and the result is a = -1
It seems like the value for a being displayed is the value of a after the line of code is executed. I'm sure that has something to do with the order of operations, but I'm not sure how to get around that. Any help is greatly appreciated.

The order in which arguments to operators or functions are evaluated is undefined in C++. If the evaluation of the different arguments have side effects, these can happen whenever the compiler sees fit and if there multiple modifications to the same object the result is undefined behavior. If you want to force a specific evaluation order, you'd need to break your expression down into multiple separate expression as these are evaluated in order or you could inject operators which create a sequence point. However, the operators creating a sequence point don't play nicely with chaining output operators. The list of operators forcing the first argument to be evaluate before the other arguments are:
the , operator
the logical && and || operators
the conditional operator ?:
Of course, if you overload any of these operators, they stop introducing a sequence point as they become normal function calls.

All the operators you have listed are comparison operators which return value true or false.
Except: -=, /= and %= operators
a-=b is actually a=a-b.
Just check if you are sure that you wanted this in first place?
BTW: if(a=b) is also returns true since it is always success but I do not think we do this intentionally.

Related

Very basic calculator issues

I'm a fairly new to c++. I'm trying to create a very basic calculator and the results I'm getting are completely wrong. I've come to a standstill after 2 hours of trying everything in my knowledge. What am I doing wrong?
#include <iostream>
using namespace std;
int main()
{
int a = 0.0;
int b = 0.0;
float sum = 'a' + 'b';
float diff = 'a' - 'b';
float prod = 'a' * 'b';
float quot = 'a' / 'b';
float rem = 'a' % 'b';
//Input
cout << "Enter a number: " << endl;
cin >> a;
cout << "Enter another number: " << endl;
cin >> b;
cout << a << " + " << b << " = " << sum <<endl;
cout << a << " - " << b << " = " << diff <<endl;
cout << a << " / " << b << " = " << quot <<endl;
cout << a << " * " << b << " = " << prod <<endl;
cout << a << " % " << b << " = " << rem <<endl;
return 0;
}
you are calculating with character literals. 'a' is not the same as a here.
remove the quotes when calculating, but add them when you print the actual literal "a"
float sum = 'a' + 'b';
You are calculating the ASCII value of the character "a" (which is 65) with the ASCII value of "b" (which is 66)
It should be
float sum = a + b;
instead.
When you print the values, you did the reverse:
cout << a << " + " << b << " = " << sum <<endl;
You want it to be
cout << "a" << " + " << "b" << " = " << sum <<endl;
instead. You want to print characters for the equation and only a number for the result.
You also calculate the values of a and b before they have an actual value.
You should put the calculation after you enter them.
Fixed, by moving the calculations after the input; and by using variables, not literals.
#include <iostream>
using namespace std;
int main()
{
int a = 0.0;
int b = 0.0;
//Input
cout << "Enter a number: " << endl;
cin >> a;
cout << "Enter another number: " << endl;
cin >> b;
float sum = a + b;
float diff = a - b;
float prod = a * b;
float quot = a / b;
float rem = a % b;
cout << a << " + " << b << " = " << sum <<endl;
cout << a << " - " << b << " = " << diff <<endl;
cout << a << " / " << b << " = " << quot <<endl;
cout << a << " * " << b << " = " << prod <<endl;
cout << a << " % " << b << " = " << rem <<endl;
return 0;
}

Need Help Operator Overloading So I Can Display Functions

I'm stuck trying to figure out how to overload the << operator so I can display my rational class functions.
These are the lines I'm trying to overload:
cout << "Testing the compare() member function, found:" << endl;
if (r1.compare(r2) == 1)
cout << r1.display() << " is greater than " << r2.display() << endl;
else if (r1.compare(r2) == 0)
cout << r1.display() << " is equal to " << r2.display() << endl;
else if (r1.compare(r2) == -1)
cout << r1.display() << " is less than " << r2.display() << endl;
cout << "Testing the four arithmetic member functions:" << endl;
cout << "r1 + r2 = " << r1.display() << " + " << r2.display() << " = " << r1.add(r2) << endl;
cout << "r1 - r2 = " << r1.display() << " - " << r2.display() << " = " << r1.subtract(r2) << endl;
cout << "r1 * r2 = " << r1.display() << " * " << r2.display() << " = " << r1.multiply(r2) << endl;
cout << "r1 / r2 = " << r1.display() << " / " << r2.display() << " = " << r1.divide(r2) << endl;
The errors occur everytime I call a function. Here is the code for the functions:
void rational::display()
{
int gcd = GCD();
if (denom < 0)
{
num = -num;
cout << num / gcd << " / " << denom / gcd << endl;
}
else if (num == 0)
cout << num << endl;
}
rational rational::add(const rational &r2) const
{
rational sum;
sum.num = (num * r2.denom) + (r2.num * denom);
sum.denom = denom * r2.denom;
return sum;
}
The multiply, divide, and subtract functions are as same as the add they just have the symbols and variable name changed to match the operation. My overload operator is set up like this:
ostream& operator<< (ostream& out, rational &robj)
{
out << example code << example code;
return out;
}
Any help would be appreciated. This is my first time posting so if I need to post more of my code I will. Thanks!
First of all, change
ostream& operator<< (ostream& out, rational &robj)
to
ostream& operator<< (ostream& out, rational const& robj)
Then, instead of
cout << r1.display() << " is greater than " << r2.display() << endl;
use
cout << r1 << " is greater than " << r2 << endl;
Since you already have the above operator<< function, I would get rid of the member function display(). It doesn't (should not) give you any more functionality than using the operator<< function.
Given
rational 1
Use of
r.display();
should give you the same output as
cout << r << endl;
See What are the basic rules and idioms for operator overloading? for more details on operator overloading.

C++ - Multiplying / adding, two integers, then determining if they are even or odd

I'm having trouble with a simple program which will multiply 2 integers and print the output determining if it is even or odd. It also will add the 2 integers input in the beginning and do the same on the following line. The multiplying works fine and displays if the product is even or odd properly. However, the addition is not doing so and I am not understanding why. Here is my code:
#include <iostream>
using namespace std;
int main (){
int a, b;
cout << "Please enter an integer: ";
cin >> a;
cout << "Please enter another integer: ";
cin >> b;
if (a*b %2== 0){
cout << "The product of " << a << " and " << b << " is " << (a*b)
<< " and is even." << endl;
}
else {
cout << "The product of " << a << " and " << b << " is " << (a*b)
<< " and is odd." << endl;
};
if (a+b %2== 0){
cout << "The sum of " << a << " and " << b << " is " << (a+b)
<< " and is even." << endl;
}
else {
cout << "The sum of " << a << " and " << b << " is " << (a+b)
<< " and is odd." << endl;
}
return (0);
}
Any help and an explanation would be greatly appreciated. Thanks!
Operator Precedence
Basically, % is dealt with before +, so your test:
if (a+b % 2 == 0)
works out like
if (a + (b%2) == 0)
which doesn't make a whole lot of sense, and is rarely going to be true, unless both b is even and a is 0.
All the operations that are to do with multiplication (*, /, %) have the same precedence, and are handled from left-to-right, so
if (a*b % 2 == 0)
works out ok, as:
if ((a*b) % 2 == 0)
which happens to be what you really meant.
However, these multiplication operations are handled before the operations related to addition (+, -). So % is grouped before +, causing your specific problem.
You may have learnt about order of operations in school, for instance I was taught BODMAS. Same rules apply in C++.
Personally, I find it's best to use parentheses liberally in any sort of compound expression, even when it's not strictly necessary. It can make the code a lot easier to read, rather than trying to remember all the rules in your head. So I would prefer:
if ((a*b) % 2 == 0) // ...
if ((a+b) % 2 == 0) // ...
even though the extra parentheses in the first aren't really required.
Operator precedence says that % comes before + so
a+b %2== 0
Is actually
a + (b % 2) == 0
You need to wrap the addition with ()
(a + b) % 2 == 0
Possibly Order of Operations.
To ensure that your code is behaving the way you intend, you may wish to rewrite it like this:
if (((a*b) %2)== 0){
cout << "The product of " << a << " and " << b << " is " << (a*b) << " and is even." << endl;
}
else {
cout << "The product of " << a << " and " << b << " is " << (a*b) << " and is odd." << endl;
};
if (((a+b) %2)== 0){
cout << "The sum of " << a << " and " << b << " is " << (a+b) << " and is even." << endl;
}
else {
cout << "The sum of " << a << " and " << b << " is " << (a+b) << " and is odd." << endl;
}
You can then incrementally remove parenthesis until you're confident that the code is readable but still correct.

C++ assignment help on creating codes for reusability?

I've been having trouble doing this assignment. I'm just having a hard time understanding and I am not entirely sure what to do. I've researched and watched videos and havent been able to find the right, specific information. Its a bunch of questions, so I hope someone can not only giveme the answers, but also explain to me so I have a strong understanding :) . Here are the questions:
1)In this exercise we have been given some program code that will accept two integers as inputs
and evaluate which one holds the larger value. This evaluation occurs in multiple places
throughout the code. Write a function that the program could use to perform this same evaluation
instead of duplicating the code over and over. Start by writing a suitable function declaration
towards the beginning of the code file. You will have to decide whether your function will return
some output or not.
2) With your declaration written proceed to define the function, including the appropriate pieces of
code that will evaluate which of the two integers is the largest. If you stated earlier that your
function will return a value, be sure to define what it will return here.
3) Use your result from parts (1) and (2) to reduce the amount of duplicate code in the main function
provided by replacing the multiple instances of the integer comparison with a call to invoke the
function you have created. Remember that the function will require two integers to be passed in
as arguments and if you are returning some value from the function it should be used (stored in
a variable, outputted to screen, etc.). As a word of advice, test your function works correctly after
replacing just one of the evaluations, don’t replace them all at once (if the function works correctly
for the first replacement then it should work for the others).
4) Since the function you have created only compares the values of its parameters and doesn’t write
to them (i.e. change the value stored in them) we should specify in the function declaration and
definition that these parameters should be treated like constants. Make the necessary
modifications to the function and test again to verify the function still works. Confirm the function
will not let you change the data of the parameters by trying to include an operation in the function
that would change the value of one of the variables (e.g. number2 += 10;)
-- Here is the code ( I apologise for the long writing):
#include <iostream>
int main(void)
{
using std::cout;
using std::cin;
using std::endl;
int nNum1 = 10, nNum2 = 11;
cout << "This program will compare two numbers and report which one is larger.\n\n"
<< "Proceeding with evaluation...\n" << endl;
cout << "\nUsing numbers: " << nNum1 << " and " << nNum2 << ", the larger one is: ";
if (nNum1 > nNum2)
cout << nNum1 << endl;
else if (nNum1 < nNum2)
cout << nNum2 << endl;
else
cout << "Neither of them! It's a draw." << endl;
int numberA = 234;
int numberB = 234;
cout << "\nUsing numbers: " << numberA << " and " << numberB << ", the larger one is: ";
if (numberA > numberB)
cout << numberA << endl;
else if (numberA < numberB)
cout << numberB << endl;
else
cout << "Neither of them! It's a draw." << endl;
int one = 'a';
int two = 'A';
cout << "\nUsing numbers: " << one << " and " << two << ", the larger one is: ";
if (one > two)
cout << one << endl;
else if (one < two)
cout << two << endl;
else
cout << "Neither of them! It's a draw." << endl;
cout << "\nUsing numbers: " << 13 << " and " << 84 << ", the larger one is: ";
if (13 > 84)
cout << 13 << endl;
else if (13 < 84)
cout << 84 << endl;
else
cout << "Neither of them! It's a draw." << endl;
int input1 = 0;
int input2 = 0;
cout << "\nPlease enter a number: ";
cin >> input1;
cout << "\nPlease enter a second number: ";
cin >> input2;
cout << "\nUsing numbers: " << input1 << " and " << input2 << ", the larger one is: ";
if (input1 > input2)
cout << input1 << endl;
else if (input1 < input2)
cout << input2 << endl;
else
cout << "Neither of them! It's a draw." << endl;
cout << "\n\tThank you for running me :3\n" << endl;
return 0;
}
You basically have to refactor the code to replace the duplicate code part in your main function.
If you look closely you will see that code like this repeats:
cout << "\nUsing numbers: " << nNum1 << " and " << nNum2 << ", the larger one is: ";
if (nNum1 > nNum2)
cout << nNum1 << endl;
else if (nNum1 < nNum2)
cout << nNum2 << endl;
else
cout << "Neither of them! It's a draw." << endl;
So put that into a function:
void CompareNumbers(int nNum1, int nNum2)
{
cout << "\nUsing numbers: " << nNum1 << " and " << nNum2 << ", the larger one is: ";
if (nNum1 > nNum2)
cout << nNum1 << endl;
else if (nNum1 < nNum2)
cout << nNum2 << endl;
else
cout << "Neither of them! It's a draw." << endl;
}
And call this in your main function instead of duplicating the said code block.

c++11 lambda capturelist reference [duplicate]

This question already has answers here:
ostream chaining, output order
(5 answers)
Closed 8 years ago.
below is my practice code about c++11 lambda:
#include<iostream>
int d = 0;
int main()
{
int e = 1;
auto i = [&]() ->int {
e += 1;
d += 1;
return d;};
d += 1;
std::cout << "the value of d:" << d << std::endl;
std::cout << "the value of i():" << i() << std::endl << " e:" << e << " d:" << d << std::endl;
std::cout << " e:" << e << " d:" << d << std::endl;
return 0;
}
and i got result not as expected:
the value of d:1
the value of i():2
e:1 d:1
e:2 d:2
I just don't understand why
std::cout << "the value of i():" << i() << std::endl << " e:" << e << " d:" << d << std::endl;
std::cout << " e:" << e << " d:" << d << std::endl;
this two lines give different out put of e and d?
ps:forgive my bad english
The evaluation order of the operands of << isn't specified; so it's unspecified whether the values of e and d in the first line are taken before or after they're incremented by the call to i().
So you might get the values before or after they're incremented, depending on the whim of the compiler.
The second line is sequenced after the first, so you'll definitely get the incremented values there.
The order of evaluation of function arguments is unspecified. So function arguments can be evaluated right to left or left to right.
It seems that your compiler evaluates arguments from right to left. So in this statement
std::cout << "the value of i():" << i() << std::endl << " e:" << e << " d:" << d << << std::endl;
the compiler at first evaluates d that is equal to 1 then e that is equal also to 1 and only after that it evaluates i() that returns 2. So you get the following output
the value of i():2
e:1 d:1
Take into account that in this statement using of operator << is equivalent to a call of an appropriate overloaded operator function with the corresponding arguments.
For example this code snippet
int a = 10, b = 20;
std::cout << a << ' ' << b;
is equivalent to
int a = 10, b = 20;
std::operator <<( std::cout.operator <<( a ), ' ' ).operator <<( b );
To get the expected result you should split the original statement into
std::cout << "the value of i():" << i() << std::endl
std::cout << " e:" << e << " d:" << d << << std::endl;