Bài tập C++ trên hackerank

Task
Given an integer,n , perform the following conditional actions:

If N is odd, print Weird
If N is even and in the inclusive range of to N, print Not Weird
If N is even and in the inclusive range of to N, print Weird
If N is even and greater than N, print Not Weird
Complete the stub code provided in your editor to print whether or not N is weird.

Bài tập khá dễ nhưng khi code thì mình lỗi ngay :frowning:
Code của mình :slight_smile:
int N;
cin >> N;

if (N % 2 == 0) {
	if (N>20) {
		cout << "Not Weird" << endl;
	}
	if ( 2 <= N <= 5) {
		cout << "Weird" << endl;

	}
	if (6 <= N <= 20)
		cout << "Not Weird" << endl;
}
else {
	cout << "Weird" << endl;
}
system("pause");
return 0;

}
Code đúng :frowning:
int main(){
int N;
cin >> N;

if (N%2 == 0) {
	if (N>20) {
		cout << "Not Weird" << endl;
	}
	if (N>=2 && N <= 5) {
		cout << "Weird" << endl;

	}
	if (6 >= N && N <= 20)
		cout << "Not Weird" << endl;
}
else {
	cout << "Weird" << endl;
}
system("pause");
return 0;

}
Tại sao nó lại khác nhau nhỉ theo toán mình đã được học cấp 3 thì 3 < N < 5 cũng bằng với 3 < N và N <5 mà nhỉ.

3 < N < 5 tức là (3 < N) < 5, mà 1 biểu thức so sánh trả về 0 hay 1 nên luôn đúng.

3 Likes

cảm ơn bạn nhiều nhé :smile:

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