#06:プログラムで計算する
ここでは、プログラムで計算する方法を学習します。まずは、整数の四則演算を試してみましょう。
掛け算は、「アスタリスク」を使って、割り算には、「スラッシュ」を使います。
+:足し算
-:引き算
*:掛け算
/:割り算
#include <iostream>
using namespace std;
int main() {
cout << 100 + 30;
}
// 130
#include <iostream>
using namespace std;
int main() {
cout << 100 - 30;
}
// 70
#include <iostream>
using namespace std;
int main() {
cout << 100 * 30;
}
// 3000
整数同士の割り算は、答えも整数になります。
#include <iostream>
using namespace std;
int main() {
cout << 100 / 30;
}
// 3
・式は、複数の演算子を使うことができます。複数の演算子がある場合は、左から順番に計算していきます。
#include <iostream>
using namespace std;
int main() {
cout << 100 + 30 + 2;
}
// 132
・掛け算や割り算は、足し算や引き算より先に計算します。
#include <iostream>
using namespace std;
int main() {
cout << 100 + 30 * 2;
}
// 160
・カッコがあると、その中を先に計算します。
#include <iostream>
using namespace std;
int main() {
cout << (100 + 30) * 2;
}
// 260