在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;
}
以上三種方法都可以實現條件判斷,根據具體需求和場景選擇合適的方法。