在C++中,可以使用if-else语句、switch语句或者三元运算符(条件运算符)来实现条件判断。下面是这三种方法的示例:
#include <iostream>
using namespace std;
int main() {
int number = 10;
if (number > 0) {
cout << "The number is positive." << endl;
} else if (number < 0) {
cout << "The number is negative." << endl;
} else {
cout << "The number is zero." << endl;
}
return 0;
}
#include <iostream>
using namespace std;
int main() {
int day = 3;
switch (day) {
case 1:
cout << "Monday" << endl;
break;
case 2:
cout << "Tuesday" << endl;
break;
case 3:
cout << "Wednesday" << endl;
break;
case 4:
cout << "Thursday" << endl;
break;
case 5:
cout << "Friday" << endl;
break;
case 6:
cout << "Saturday" << endl;
break;
case 7:
cout << "Sunday" << endl;
break;
default:
cout << "Invalid day" << endl;
}
return 0;
}
#include <iostream>
using namespace std;
int main() {
int number = 10;
string result = (number > 0) ? "The number is positive." : (number < 0) ? "The number is negative." : "The number is zero.";
cout << result << endl;
return 0;
}
以上三种方法都可以实现条件判断,根据具体需求和场景选择合适的方法。