I am a beginner, and I created a slot machine simulator. The wheel is spun and x, y, and z are set to random numbers. I have an if statement that checks to see if x == y == z. When the program runs, and the numbers are in fact equal, it runs my code that says they are not equal. Why does this happen?
For example, the cout statement will say 2 -- 2 -- 2, then it goes to my if statement for when they are not equal, and I get the "you lose" code.
I should add, this does not happen every time. Sometimes it properly executes the if statement for when they are equal. It is very odd.
srand(time(0));
int x = (rand() % 2) + 1;
int y = (rand() % 2) + 1;
int z = (rand() % 2) + 1;
std::cout << "The spin results are... " << x << " -- " << y << " -- " << z << std::endl << std::endl;
if( x == y == z)
{
std::cout << "You win!\n\n";
playerCoins = playerCoins + (coinsBet * 2);
}
else
{
std::cout << "You lose!\n\n";
}
x == y may result in 0 or 1, depending on their true or false value. Then 0 or 1 is compared with z, this why the given result is false.
The correct method is to check if x equals z and y equals z, which of course also means that x equal y. (x == z) && (y == z)
x == y == z does not do what you think it does. Use x == y && y == z instead.
The expression if (x == y == z) is evaluated to false.
Pretend x, y, and z all hold the value 2:
Because (x == y) is then true / 1. And z is holding the value 2, the if statement will check:
if ((x == y) == z)
// 1 == 2
Which becomes:
if (1 == 2) {} // false
You can fix that by doing this:
if ((x == y) && (y == z)) { /* ... */ }
You should use Logical operators.
the expression, x == y == z is wrong.
it should be done this way.
if((x == y) && (y == z)) { //or... if ((x == y) == z)
//your code goes here...
}
More information about logic operators, Here.
Related
I have a square matrix, 40 x 40, and a draw circle function that uses this formula.
I have another function that reads input from a file, the point itself (x0, y0) and the type of circle (0 or 1) and the radius.
void cerc(int x0, int y0, int r, int** matriceHarta, int tip, int n, int m)
{
if (r == 0)
return;
int x, y, xx, rr;
for (rr = r * r, x = -r; x <= r; x++)
for (xx = x * x, y = -r; y <= r; y++)
if (xx + (y * y) <= rr && matriceHarta[x0 + x][y0 + y] == 0)
{
if (tip == 0)
matriceHarta[x0 + x][y0 + y] = -5;
else if (tip == 1)
matriceHarta[x0 + x][y0 + y] = -6;
}
}
N and M are the rows and columns, but right now they are both equal.
The matrix is allocated dynamically and is transmitted via the int** matriceHarta parameter.
If I put the point on (39, 39) and I give it the radius 5, the program returns a negative exit code, which I found out is an out of bounds related error. I looked over the for loops and it makes sense that that'd be the error and tried to create the condition if((x0 + x) < n && (y0 + y) < m) to check the bounds, but it still gives the error.
Question is, what am I doing wrong? For contrast, point(37, 4) with radius = 2 is OK, but point(38, 4) with radius = 2 is not OK
This is the attempted fix:
for (rr = r * r, x = -r; x <= r; x++)
for (xx = x * x, y = -r; y <= r; y++)
if (xx + (y * y) <= rr && matriceHarta[x0 + x][y0 + y] == 0
&& (((x0+x) < n) && ((y0+y) < m)) )
//^^^^^ this is the condition i was talking about
{
if (tip == 0)
matriceHarta[x0 + x][y0 + y] = -5;
else if (tip == 1)
matriceHarta[x0 + x][y0 + y] = -6;
}
The issue is that you are testing for the out-of-bounds condition after you have already accessed potential out-of-bounds elements.
Let's break it down into separate lines:
if (xx + (y * y) <= rr && matriceHarta[x0 + x][y0 + y] == 0
&& // <-- This binds the conditions
(((x0+x) < n) && ((y0+y) < m)))
The line above the && marked with <-- is evaluated before the line below the <--.
In summary, the logical && is always evaluated from left-to-right, where the right side will not be evaluated if the left side evaluates to false (short-circuit boolean evaluation).
Thus the fix is to test the bounds condition first (swap the lines in the code above).
However, to make this a little more clear, you could break up the statement into two if statements:
if (x0+x < n && y0+y < m)
{
if (xx + (y * y) <= rr && matriceHarta[x0 + x][y0 + y] == 0)
{
...
}
}
I did a recursive function to calculate x*y with x and y are all integers (x and y >= 0). My formula is:
x * y =
0, if x is equal 0
(x >> 1)*(y << 1), if x is an even number
(x >> 1)*(y << 1) + y, if x is an odd number
"<<" and ">>" are Left Shift and Right Shift Bitwise Operator. Here is my code:
int multiply(int x, int y) {
int y1 = 0;
if (x == 0) return 0;
else if (x % 3 == 0) {
y1 = y;
x = x >> 1;
y = y << 1;
return (multiply(x, y) + y1);
}
else if (x % 2 == 0) {
x = x >> 1;
y = y << 1;
return multiply(x, y);
}
}
The recursive function above is supposed to return (x*y) value but they were all wrong when i tested and i don't know why. What did i do wrong? How can i fix this?
Your problem is wit x % 3, what happens if x = 5? you skip it. Here is improved version of your code.
int multiply(int x, int y) {
if (x == 0)
return 0;
else if (x % 2 == 1)
return (multiply(x >> 1, y << 1) + y);
return multiply(x >> 1, y << 1);
}
or maybe even this:
int multiply(int x, int y) {
if (x == 0)
return 0;
int m = multiply(x >> 1, y << 1);
if (x % 2 == 1)
m += y;
return m;
}
Here is super fast version suggested by Andy:
int multiply(int x, int y) {
if (x == 0)
return 0;
int m = multiply(x >> 1, y << 1);
if (x & 1)
m += y;
return m;
}
As a challenge of speed, here is non recursive version:
int multiply (int x, int y) {
int y1 = 0;
for (; x > 0; x = (x >> 1), y = (y << 1))
if (x&1)
y1 += y;
return y1;
}
NOTE: I know this question is about recursive method but just as a challenge I wrote non-recursive algorithm.
You are not checking if x is odd correctly here:
else if (x % 3 == 0) { // e.g. fails on x = 1
Instead, you need to do
else if (x % 2 == 1) {
Here's a demo.
Note that this makes the following else check for even values of x redundant:
else if (x % 2 == 0) { // can just be an unconditional else
Also, since you are returning from the x == 0, and x % 2 == 1 branches, the else conditions can be removed as well. You can also factor out the repeated code to make the function simpler, like this:
int multiply(int x, int y) {
if (x == 0) return 0;
if (x % 2 == 1)
return (multiply(x >> 1, y << 1) + y);
else
return multiply(x >> 1, y << 1);
}
Here's a demo.
This is what i feel is the simplest approach to carry out recursive multiplication.
Do let me know if its efficient enough for you.
#include<iostream>
using namespace std;
float multiply(float a, float b) {
//no zeros bro
if (b == 0)
return 0;
//let the recursion begin
if (b > 0)
return x + multiply(a, b - 1);
//negatives stay away pliz
if (y < 0)
return -multiply(a, -b);
}
int main() {
float a, b, result;
cout << "Enter the two numbers";
cin >> a >> b;
result = multiply(a, b);
//And the result is.................
cout << result;
return 0;
}
Recursive function related to multiplication of natural numbers:
int multCool(int a, int b)
{
return (b==1 ? a: a+ multCool(a,b-1));
}
I am trying to solve a very simple equation in c++ by brute force. The basic idea is to run up or down the value of x until the left side of the equation is equal to the right side. I am not getting any errors, but the value of x is always either 0.01 or -0.01. I assume that my do/while loop is flawed, but you are all probably more experienced than I am, so any help is appreciated.
#include <iostream>
using namespace std;
int main()
{
double x, y, z, q, w;
x = 0;
cout << "enter y*x + q = z*x + w in order of appearance" << endl;
cin >> y;
cin >> q;
cin >> z;
cin >> w;
if ((y-z)/(w-q) > 0) // checks if x is positive
{
do
{
(x = x + 0.01);
} while ((y * x + q) == (z * x + w));
}
else if ((y - z) / (w - q) < 0) // checks if x is negative
{
do
{
(x = x - 0.01);
} while ((y * x + q) == (z * x + w));
}
else
{
x = 0;
}
cout << "x is " << x << endl;
return 0;
}
Thanks!
A few things.
First, when comparing floats, you probably want to do so within a tight range, frequently referred to as epsilon. This is especially true because you're incrementing by a fairly wide margin -- 0.01. You are probably skipping over the value you want.
What I would do is pay attention to:
Am I getting closer or further from the answer?
And did I skip over the answer?
Some code:
float leftSide = y * x + q;
float rightSide = z * x + w;
float delta = leftSide - rightSide;
if (abs(delta) < epsilon) {
// You're really close
}
Note also this will never work if y and z are identical values unless q and w are as well.
The problem
I'm new to this sort of programming, and my C++ maze solver is stuck in a loop.
The maze is a simple char 2-D matrix with an asterisk (*) for a valid path square, and a slash (/) for a wall square.
Why doesn't the program stop when it finds a '/'?
# include < iostream >
using namespace std;
char lab[6][6] =
{ { '/','/','/','/','/' },
{ '/','*','/','/','/' },
{ '/','*','*','*','/' },
{ '/','/','*','/','/' },
{ '/','/','*','/','/' },
{ '/','/','*','*','*' } };
int x, y;
void run(char lab[][6], int, int);
bool movU() // Move Up
{
if (lab[x][y - 1] == '*')
return true;
else
return false;
}
bool movR() // Move right
{
if (lab[x + 1][y] == '*')
return true;
else
return false;
}
bool movD() // Move Down
{
if (lab[x][y + 1] == '*')
return true;
else
return false;
}
bool movL() // Move Left
{
if (lab[x - 1][y] == '*')
return true;
else
return false;
}
void run(char lab[][6], int x, int y)
{
if (movU() == true) // I'm getting stuck right here
run(lab, x, y - 1); // Getting negative numbers here
else if (movR() == true)
run(lab, x + 1, y);
else if (movD() == true)
run(lab, x, y + 1);
else if (movL() == true)
run(lab, x - 1, y);
else
cout << "Error" << endl;
}
int main()
{
x = 1, y = 2; // Start position
run(lab, x, y);
return 0;
}
Besides the global scoping problem with x and y, you haven't done anything to keep the subscripts from running over the edge of the maze into random memory locations. As a result, y continues to decrement, and you back up through memory looking for an asterisk. Since you also recur, you continue this until you blow all your stack space.
Also, you don't seem to be comfortable with boolean values yet: you do a lot of extra work to deal with constants true and false, rather than simply using the value of a boolean expression.
I've fixed these items in your code:
# include <iostream>
using namespace std;
char lab[6][6] =
{
{ '/','/','/','/','/' },
{ '/','*','/','/','/' },
{ '/','*','*','*','/' },
{ '/','/','*','/','/' },
{ '/','/','*','/','/' },
{ '/','/','*','*','*' }
};
void run(char lab[][6], int, int);
bool movU(int x, int y) // Move Up
{
return x >= 0 && y >= 1 &&
x < 6 && y < 6 &&
lab[x][y - 1] == '*';
}
bool movR(int x, int y) // Move right
{
return x >= 0 && y >= 0 &&
x < 5 && y < 6 &&
lab[x+1][y] == '*';
}
bool movD(int x, int y) // Move Down
{
return x >= 0 && y >= 0 &&
x < 6 && y < 5 &&
lab[x][y + 1] == '*';
}
bool movL(int x, int y) // Move Left
{
return x >= 1 && y >= 0 &&
x < 6 && y < 6 &&
lab[x-1][y] == '*';
}
void run(char lab[][6], int x, int y)
{
cout << "ENTER run; x = " << x << "\ty = " << y << endl;
if (movU(x, y)) // I'm getting stuck right here
run(lab, x, y - 1); // Getting negative numbers here
else if (movR(x, y))
run(lab, x + 1, y);
else if (movD(x, y))
run(lab, x, y + 1);
else if (movL(x, y))
run(lab, x - 1, y);
else
cout << "Error" << endl;
}
int main()
{
// x = 1, y = 2; // Start position
run(lab, 1, 2);
return 0;
}
This stays within bounds ... and loops until it runs out of stack space. You need to add code to avoid rechecking ground you've already visited. For instance, you can mark the location with another character, such as an underscore.
You also need to recognize when you're done. What marks the maze exit? You'll need a check in your run routine for that.
why the result is x=1 y=3 res=1
int x = 7, y = 3;
int res;
res = (x = y < 2 || x != 1);
printf("x = %d y = %d res = %d\n", x, y, res);
and with this code the result is y<2 so False which is 0 so lvalue x = 0 so the res=0
res= (x = y < 2); //|| x != 1);
printf("x = %d y = %d res= %d\n", x, y, res);
res = (x = y < 2 || x != 1);
...is evaluated as...
res = (x = ((y < 2) || (x != 1)));
You can find the Operator Precendence for C++ here - C is similar for the operators you've used.
So for x = 7, y = 3...
res = (x = ((3 < 2) || (7 != 1)));
res = (x = (false || true)); // || is "logical-OR", tests if either true
res = (x = true);
res = (x = 1); // standard conversion from bool to int
res = 1;
For your second, simpler statement:
res = (x = y < 2);
res = (x = (y < 2));
res = (x = (3 < 2));
res = (x = false);
res = (x = 0); // standard conversion from bool false to int 0
res = 0;
In C, even if you #include <stdbool.h> the <, != and || operators will yield 1 immediately for "true" tests, and 0 for "false", and there's no separate "standard conversion" as in C++. Allan's answer describes the C evaluation steps nicely.
res = (x = y < 2 || x != 1);
In above statement y < 2 || x != 1 is a conditional expression whose result is true (1) which is loaded into x.
Now, (x = y < 2 || x != 1) evaluated as x = 1 and hence res = x = 1
This you get res and x equals to 1 and y unchanged.
The issue you seem to be having is operator precedence. The link is to an operator precedence chart which should help clear things up.
First you should know that comparisons result in either a 1 or a 0. For example, (5 < 10) returns 1 because it is true, and (5 > 10) returns 0 because it is false.
In your example, it's easier if we clarify it by adding parenthesis to show the order things are happening in.
res = (x = **(y < 2)** || **(x != 1)**)
This is the first set of operations that happens. After those resolve we are left with:
res = (x = **(0)** || **(1)**)
The next operation to take place is the OR:
res = (x = **(0 || 1)** )
This results in a 1:
res = (x = **1** )
then the assignment operation happens:
res = (**x = 1**)
then the next assignment happens:
**res = x**
Since x is equal to 1 from the previous assignment, res is also set to 1.
Not sure what you're asking in the second bit, so if you want to clarify that I'll answer for you.
< has higher precedence than = and therefore x = y < 2 is equivalent to x = (y < 2).
Since y is greater than 2 therefore y < 2 will give 0 and this value will be assigned to x. Now x is equal to 0 therefore x != 1 will be evaluated as true and the value of the whole expression x = y < 2 || x != will be 1 and this value is assigned to res.
In this case operator precedence will work.
res = (x = y < 2 || x != 1);
In this expression, first y < 2 is evaluated.
Then or(||) will work, because of first condition fails, so now the x is not equal to 1. so the condition will became true so the true value 1 is stored x and in the res variable.
(y < 2 || x != 1 ). // expression is true. So the value 1 is stored in the variable x and ret.
In second case,
y < 2; // this condition will become false. So the zero is stored in both the variable.