第八回: 控制程式流程的敘述
if 敘述
型態一:
if (條件運算式)
敘述;
型態二:
if (條件運算式)
{
敘述一;
敘述二;
...
}型態三:
if (條件運算式)
{
敘述一;
敘述二;
...
}
else
{
敘述一;
敘述二;
...
}
switch...case 敘述
switch (運算式)
{
case (值一):
敘述一;
敘述二;
...
break;
case (值二):
敘述一;
敘述二;
...
break;
...
default:
敘述一;
敘述二;
...
}
for 敘述
for (啟始運算式 ; 邏輯運算式 ; 變異運算式)
{
敘述一;
敘述二;
...
}
while 敘述
while (邏輯運算式)
{
敘述一;
敘述二;
...
}
do...while 敘述
do
{
敘述一;
敘述二;
...
} while (邏輯運算式);
do...until 敘述
do
{
敘述一;
敘述二;
...
} until (邏輯運算式);
範例:
#include <cstdlib> #include <iostream> using namespace std; int main(int argc, char *argv[]) { double a, b, c; char op; cout << "Please input a : "; cin >> a; cout << "Please input b : "; cin >> b; cout << "Please input the operator ('+', '-', '*', '/') : "; cin >> op; switch (op) { case '+': c = a + b; break; case '-': c = a - b; break; case '*': c = a * b; break; case '/': if (b == 0) cout << "b can't be zero !!!" << endl; else c = a / b; break; default: cout << "Your input operator must be '+', '-', '*', or '/' !!!" << endl; } cout << a << op << b << "=" << c << endl; system("PAUSE"); return EXIT_SUCCESS; }
練習:
Last update : 2006年2月17日