Why the console printf 3 lines although I set conditional

#include <iostream>
using namespace std;
void main()
{
	
	char one, two;
	
	cout << "Nhap vu khi nguoi choi 1 "<< endl;
	cin >> one;
	cout << "Nhap vu khi nguoi choi 2 "<< endl;
	cin >> two;
	// dieu kien hoa nhau
	if (one == 'b' && two == 'b' || one == 'o' && two == 'o' || one == 'k' && two == 'k'){
		cout << "hoa nhau" << endl;
	}
	else{
		// dieu kien thang thua
		if (one == 'b' && two == 'o'){
			cout << "Nguoi cho thu 2 thang" << endl;
		}
		else {
			cout << "Nguoi choi thu 1 thang" << endl;
		}
		if (one == 'k' && two == 'b'){
			cout << "Nguoi cho thu 2 thang" << endl;
		}
		else {
			cout << "Nguoi choi thu 1 thang" << endl;
		}
		if (one == 'o' && two == 'k'){
			cout << "Nguoi cho thu 2 thang" << endl;
		}
		else {
			cout << "Nguoi choi thu 1 thang" << endl;
		}
	}
	system("pause");
}

Result of program:

Nhap vu khi nguoi choi 1
b
Nhap vu khi nguoi choi 2
k
Nguoi choi thu 1 thang
Nguoi choi thu 1 thang
Nguoi choi thu 1 thang
Press any key to continue . . 

Help me how to fix it, please. Some information about variables:

b = búa; o = bao; k = kéo;
  • Because you use if … else … condition 3 time, so each time it will print a line even if the condition is true or false

  • To fix this, instead of using 3 if … else … , you should use if … else ladder like this:

	if (one == 'b')
	{
		if(two == 'k')
			cout << "Nguoi cho thu 1 thang" << endl;
		else
			cout << "Nguoi cho thu 2 thang" << endl;
	}
	else if (one == 'k')
	{
		if(two == 'o')
			cout << "Nguoi cho thu 1 thang" << endl;
		else
			cout << "Nguoi cho thu 2 thang" << endl;
	}
	else //if (one == 'o')
	{
		if(two == 'b')
			cout << "Nguoi cho thu 1 thang" << endl;
		else
			cout << "Nguoi cho thu 2 thang" << endl;
	}
3 Likes

Okay thanks, I have already understood my problem, thanks for giving me a solution :smile:

you are welcome, bro.

@EmCee I’ve just edited your post, you need to use

```

not

``

In order to Markup the code.

1 Like

Thanks bro :slight_smile: I’ll improve.

1 Like

if you use english to chat or discuss, Why you use vietnamese in your code? :smile:

Why not :smile: I find it’s ok hehe

2 Likes

I quên :D. In code, i forgot use English to set name for variables.

LOL, i like this :smiley: hahaha

83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?