C++基本中の基本その5
※自分用メモ
※引用元「ローベルのC++入門講座」
【条件分岐その2】
・if 文は変数などがある値をとったときの処理を決める。
・変数や関数の戻り値などがある値をとったときの処理を決める。
#include <iostream> #include <string> using namespace std; void divide() { int a, b; cout << "Enter your first number: " << flush; cin >> a; cout << "Enter your second number: " << flush; cin >> b; if(b == 0) { cout << "You can't divide a number by 0." << endl; } else { cout << a << "/" << b << "=" << a/b << endl; } } int main() { divide(); divide(); return 0; }
結果
Enter your first number: 10 Enter your second number: 2 10/2=5 Enter your first number: 4 Enter your second number: 0 You can't divide a number by 0.