C++ if-else if Issues [closed] - c++

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm having issues with my program below. It should convert numbers between 1-100 to AA,BA,BB,CB,CC,D,F. But it stops working and shows "BA" if I enter number less than 84. I checked the code. But I don't understand what is the problem.
#include <iostream>
using namespace std;
int main() {
int secenek,notu;
cout << "Not Dönüştürücü" << endl;
cout<<"Başlamak için 1'e basın:\n";
cin>>secenek;
if (secenek==1)
{
cout<<"Dönüştürülecek not: ";
cin>>notu;
}
if (notu<0 || notu>100)
{
cout<<"Geçerli bir not girin.\n";
}
else if (notu>=90)
{
cout<<"AA";
}
else if (notu<90 || notu>84)
{
cout<<"BA";
}
else if (notu<85 || notu>79)
{
cout<<"BB";
}
else if (notu<80 || notu>74)
{
cout<<"CB";
}
else if (notu<75 || notu>69)
{
cout<<"CC";
}
else if (notu<70 || notu>59)
{
cout<<"D";
}
else if (notu<60)
{
cout<<"F";
}
}

you made a logical error:
else if (notu<90 || notu>84)
should be
else if (notu<90 && notu>84)
and the same goes for all the following conditions.
EDIT as #Jarod42 suggested; you don't even need to check notu<90 anymore... your code could look like this:
if (notu<0 || notu>100)
{
cout<<"Geçerli bir not girin.\n";
}
else if (notu>=90)
{
cout<<"AA";
}
else if (notu>84)
{
cout<<"BA";
}
else if (notu>79)
{
cout<<"BB";
}
etc...

Your condition
else if (notu<90 || notu>84)
will always be true, whatever notu is set to. You probably mean
else if (notu < 90 && notu > 84)

The problematic part:
else if (notu<90 || notu>84)
{
cout<<"BA";
}
else if (notu<85 || notu>79)
{
cout<<"BB";
}
else if (notu<80 || notu>74)
{
cout<<"CB";
}
else if (notu<90 || notu> 84) will trigger on any notu lower than 90 and on any notu higher than 84. That's all pretty much all who survived the earlier check.
Correct implementation would be else if (notu<90 && notu> 84) which will only trigger if both conditions are met.
My C++ is a bit rusty, but if I remember correctly one could even write else if (84 < notu < 90).
EDIT: else if (84 < notu < 90) isn't valid C++ syntax.

The main problem is that you're using || where && would be logically correct.
But you don't really need && either - you can simplify a bit since in the else branch you already know that the corresponding if condition is false.
Like this:
if (notu < 0 || notu > 100)
{
cout << "Geçerli bir not girin.\n";
}
else if (notu >= 90)
{
cout << "AA";
}
else if (notu >= 85) // Already know that it's < 90, because it's not >= 90
{
cout << "BA";
}
// ...
// ...
else if (notu >= 60) // Already know that it's < 70
{
cout << "D";
}
else // Already know that it's < 60
{
cout << "F";
}

Related

gtkmm keyboard events skip

Is there a way to cancel key_release event on certain conditions?
I try to explain better...I want that in an entry I can only insert numbers, if I insert another character this will be skipped.
.h file
bool on_value_change(GdkEventKey* key_event);
.c++ file
m_TxtDiversi1->signal_key_release_event().connect(sigc::mem_fun(*this, &MainWindow::on_value_change));
bool MainWindow::on_value_change(GdkEventKey* key_event)
{
if((key_event->keyval >= 48 && key_event->keyval <= 57) || (key_event->keyval >= 65456 && key_event->keyval <= 65465) || key_event->keyval == 65454)
{
std::cout << "1ui" << std::endl;
return true;
}
return false;
}
can somebody hel me please? Thanks a lot in advance.
I found a solution
m_TxtDiversi1->signal_key_press_event().connect(sigc::mem_fun(*this, &MainWindow::on_value_change), false);
bool MainWindow::on_value_change(GdkEventKey* key_event)
{
if((key_event->keyval >= 48 && key_event->keyval <= 57) || (key_event->keyval >= 65456 && key_event->keyval <= 65465) || key_event->keyval == 65454)
{
std::cout << "1ui" << std::endl;
return false;
}
return true;
}

Arduino Autonmous car if statements (ultrasonic)

I have run into a problem while creating the if statements for the autonomous car. The car skips most of the if statements and immeaditly goes to the else statement. The sensors give of the right values. Is it because i use "else if" statements or something else? The car is supposed to react to its surroundings, so i had to give it many if statements as possible. But instead it just does the last bit where it goes backwards waits goes backwards left and backwards right. So my question is do i have to add more if statements so it reacts better to its surroundings or is there more to it? Here is the code of the if statements:
if (sensors[0] >= 50 ) { //if the distance of the front sensor is greater than 50cm, than set Fwd true. Otherwise its false.
Fwd = true;
} else {
Fwd = false;
}
delay(50);
if ((Fwd == true) && (sensors[1] > 50) && (sensors[2] > 50)) {
fwd();
} else if ((Fwd == true) && (sensors[1] < 50)) {
fwdRight();
} else if ((Fwd == true) && (sensors[2] < 50)) {
fwdLeft();
} else if ((Fwd == false) && (sensors[1] < 50) && (sensors[2] < 50)) {
Stp();
} else if ((Fwd == false) && (sensors[1] < 50)) {
bwdRight();
} else if ((Fwd == false) && sensors[2] < 50) {
bwdRight();
} else {
Stp();
delay(1000);
bwd();
delay(500);
bwdLeft();
delay(500);
bwdRight();
}
Start by tidying up your code, and it may be obvious where things may be going wrong. For example, you are calling multiple checks to Fwd by doing:
if ((Fwd == true) && ... ) {
...
} else if ((Fwd == true) && ... ) {
...
} else if ((Fwd == true) && ... ) {
...
} else if ((Fwd == false) && ... ) {
...
} else if ((Fwd == false) && ... ) {
...
}
This uses up valuable resources in your program memory. It would be much more efficient to do a single check, and evaluate from there:
if (Fwd){
// Check sensor conditions here
} else {
// Check more sensor conditions here
}
In fact, you could probably omit the Fwd variable (unless you are using it elsewhere) altogether, saving you more memory space:
// Check whether to go forward or backwards.
// >= 50 - forward
// < 50 - backward
if (sensors[0] >= 50) {
// Check sensor conditions here
} else {
// Check more sensor conditions here
}
Overall, you could end up with something like:
// Check whether to go forward or backwards.
// >= 50 - forward
// < 50 - backward
if (sensors[0] >= 50) {
// Going forward, but which direction?
if (sensors[1] < 50) {
fwdRight();
} else if (sensors[2] < 50) {
fwdLeft();
} else {
// sensors[1] >= 50 AND sensors[2] >= 50
// Going straight forward
fwd();
}
} else {
// Check backward sensor conditions here
}
This answer might not directly answer your question, but it should help you diagnose better what is going on.

Can't figure out how to loop playerturns and moves Tic Tac Toe (C++) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
EDIT: Solved now thank you triple_r and AJNeufield for your help on this problem I was having.
I've looked around multiple websites and YouTube about this and I can't seem to find anything on what I am specifically looking for this as my format for the program is a good bit different than others. Therefore, it's hard to decipher where I need to put the things I do need that I know of.
Please note that I'm relatively new to C++ so I'd appreciate all the feedback or criticism you might provide me.
Also, note my code does compile and run it just does not allow me to put in more than one input and more than likely does not allow for a switch of player turns.
Quick Edit: Switched the code with the new setup suggested by triple_r but I seemed to have messed it up somewhere along the line and it does compile(with the exception of x and y not being utilized and one other error) but it always starts off with player 2 going first and as soon as it receives input it ends automatically with a segmentation fault.
#include <iostream>
#include <cstdlib>
using namespace std;
//////////////////////////////////////////////////////////
void initboard(char board[3][3])
{
int x,y;
for (x=0;x<3;x++)
for (y=0;y<3;y++)
board[x][y]=' ';
return;
}
//////////////////////////////////////////////////////////
void printboard(char board[3][3])
{
int x,y;
for (x=0;x<3;x++)
{
cout<<"\n";
for (y=0;y<3;y++)
{
cout<<" "<<board[x][y]<<" ";
if (y<2) cout<<"|";
}
if (x<2) cout<<"\n===========";
}
return;
}
//////////////////////////////////////////////////////////
void getmove(char board[3][3], int player)
{
return;
}
//////////////////////////////////////////////////////////
int main()
{
bool done=false;
char board[3][3];
int x,y,player=1,turn,playerchoice,playermark;
initboard(board);
turn=0;
do
{
if (player==1)
playermark='X';
else
playermark='O';
if (turn%2)
player=1;
else
player=2;
cout<<"Player "<<player<<" where do you want to move?: ";
cin>>playerchoice;
if (playerchoice==1)
{
board[0][0]=playermark;
}
else if (playerchoice==2)
{
board[0][1]=playermark;
}
else if (playerchoice==3)
{
board[0][2]=playermark;
}
else if (playerchoice==4)
{
board[1][0]=playermark;
}
else if (playerchoice==5)
{
board[1][1]=playermark;
}
else if (playerchoice==6)
{
board[1][2]=playermark;
}
else if (playerchoice==7)
{
board[2][0]=playermark;
}
else if (playerchoice==8)
{
board[2][1]=playermark;
}
else if (playerchoice==9)
{
board[2][2]=playermark;
}
else
{
cout<<"Invalid move ";
}
if (board[x][y]!=' ')
cout<<"Move is already taken.";
board[x][y]=playermark;
if(board[x][y]==' ')
turn++;
}while (!done);
void printboard(char board[3][3]);
return 0;
}
EDIT: based on the updated code
So, the first thing I can see is that you are using x and y in your program but you don't initialize them or assign any values to them. Also, try to use functions/classes/... yo make your code more readable. You already have a function for player move but you are not using it. You can move the large if statement inside that function and that will make your main code shorter and more readable.
Here are my comments on the main part of your program:
int main()
{
// add a new variable to see if the move was valid or not:
bool done=false, validmove = true;
char board[3][3];
int x, y, player = 1, turn = 0, playerchoice, playermark;
initboard(board);
do
{
// swap the two `if`s so you decide who`s turn it is then assign the player mark,
// also, reverse the condition to make sure turn '0' is player 1's turn.
if (!(turn % 2))
player = 1;
else
player = 2;
if (player == 1)
playermark = 'X';
else
playermark = 'O';
cout << "Player " << player << " where do you want to move?: ";
cin >> playerchoice;
// Assign `x` and `y` here instead of updating the board, because you want to make
// sure that the move is valid before putting the mark:
validmove = true;
if (playerchoice == 1)
{
x = 0; y = 0;
}
else if (playerchoice == 2)
{
x = 0; y = 1;
}
else if (playerchoice == 3)
{
x = 0; y = 2;
}
else if (playerchoice == 4)
{
x = 1; y = 0;
}
else if (playerchoice == 5)
{
x = 1; y = 1;
}
else if (playerchoice == 6)
{
x = 1; y = 2;
}
else if (playerchoice == 7)
{
x = 2; y = 0;
}
else if (playerchoice == 8)
{
x = 2; y = 1;
}
else if (playerchoice == 9)
{
x = 2; y = 2;
}
else
{
cout << "Invalid move, try again!";
// Make sure to mark the move as invalid so they get a chance to
// change their move:
validmove = false;
}
// check to see if the turn was valid:
if(validmove)
{
if (board[x][y] != ' ')
{
cout << "Move is already taken, try again";
}
else
{
board[x][y] = playermark;
turn++;
}
}
// have to make sure you have a condition for end of game. A simple
// one is to check if turn is less than `9`, otherwise the board is
// full:
if(turn == 9)
done = true;
// you probably want to add a few more checks to see who won the game.
}while (!done);
// when calling a function, no need to put the return type or parameter type:
printboard(board);
return 0;
}
========================================================================
There are two do-while loops in your program and both seem to be meant as a game loop. What I would do is:
initboard(...);
turn = 0;
do{
//this is the game loop
...;
if( validturn )
turn++;
}while(!done);
release_resources(...);
return 0;
so, you fold everything into one loop. In that loop, you want to:
find who's turn it is:
if (turn % 2)
player = 1;
else
player = 2;
get users input:
std::cin >> playerchoice;
...
convert player choice to grid location:
switch ( move )
{
case 0:
x = 0;
y = 0;
break;
case 1:
...;
...
default:
//invalid move
}
see if the move is valid:
if( board[x][y] != ' ' )
//already taken, invalid move
then apply the move:
board[x][y] = playermark;
I hope this helps.
Your cin >> playerchoice is outside your do { ... } while ( moves != 9); loop. Move it inside.

Strangeness with dynamic arrays in C++ [closed]

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 8 years ago.
Improve this question
I am honestly not quite sure what is going on here.
It has been years since I have programmed in C++, but I am trying to execute this code
short* result = new short[3];
now, I would expect that this creates an array with 3 memory locations: 0,1 and 2, but for what ever reason, this works:
result[0] = someObject::parseShort();
but this does not work:
result[1] = someObject::parseShort();
no exception is thrown, but it is like addresses 1 and 2 dont even exist? I have verified this with visual studio's debugger, and this is leading to some very interesting results when I try to read from those memory addresses, no matter what I Initially wrote to them, they always seem to return 0
Like I said, its been years since I've written anything in C++, and would appreciate someone being able to tel me what is going on? because as far as I can tell, it looks like I am defining the array right?
EDIT:
here is the rest of the relevent code:
phoneNumber::phoneNumber(string number)
{
short* nbrs = parseNumber(number);
areaCode = nbrs[0];
prefix = nbrs[1];
this->number = nbrs[2];
delete[] nbrs;
}
areaCode, prefix, and number are all members of the class.
area code gets set correctly, but prefix and number dont seem to
here is the definition of parseNumber:
short* phoneNumber::parseNumber(string num)
{
if (num == "")
throw new exception("value should not be null");
int var= 3;
short* result= new short[var];
string temp = "";
bool fail = false;
int j = 0;
bool ready = false;
num = Utils::removeSpaces(num);
if (j ==0&&num[0] != '(')
{
fail = true;
}
for (int i = 1; i < num.length(); i++)
{
if (fail)
{
throw exception("Could not parse phone number! Invalid format, expected (xxx)xxx-xxxx");
}
if (num[i] >= '0' && num[i] <= '9')
{
temp+=num[i];
continue;
}
else if (j== 0 && num[i] ==')')
{
if(temp.length() != 3)
{
fail = true;
continue;
}
ready = true;
}
else if(j==1 && num[i] =='-')
{
if(temp.length() != 3)
{
fail = true;
continue;
}
ready = true;
}
else if (j == 3 && i == num.length() -1)
{
if(temp.length() != 4)
{
fail = true;
continue;
}
ready = true;
}
else
{
fail = true;
continue;
}
if (ready)
{
result[j]= Utils::parseShort(temp);
j++;
temp = "";
ready = false;
continue;
}else
{
temp+= num[i];
}
}
if (temp.length()==4)
result[j]= Utils::parseShort(temp);
else
{
throw exception("Could not parse phone number! Invalid format, expected (xxx)xxx-xxxx");
}
return result;
}
Yes, you are defining your array right. You have a bug elsewhere in your code outside the part that constitutes your question.

A true if condition is being skipped [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm trying to figure out why this condition is being skipped.. It is a 2d array, it's pretty self explanatory what's being compared. Here's the code first followed by explanation.
if ((reversed[i][j] == true) && (circle[i][j] == 'C'))
{
reversed[i][j] == false;
}
else if (circle[i][j] == 'C')
reversed[i][j] == true;
The problem is that it's skipping the else if EVEN when it's true; I've tested using a cout just before the code where I say:
cout<<circle[i][j];
and it's showing that it is indeed 'C' this is very weird, I've never seen anything like it. I hope there's something simple I'm missing.
circle is defined as follows:
char **circle;
circle = new char *[SIZE];
for (int i = 0; i < SIZE; i++)
circle[i] = new char[SIZE];
Are you sure that you wanted to write
if ((reversed[i][j] == true) && circle[i][j] == 'C'))
{
reversed[i][j] == false;
}
else if (circle[i][j] == 'C')
reversed[i][j] == true;
instead of this?
if ((reversed[i][j] == true) && circle[i][j] == 'C')
{
reversed[i][j] = false; // assignment here
}
else if (circle[i][j] == 'C')
reversed[i][j] = true; // assignment here