Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Oppiskele Not Simple Math | Variables
Introduction to C++

book
Not Simple Math

Let’s talk about a bit more complicated math. Sometimes we have a lot of calculations. In C++ (like in math) works the operator precedence, which means that groups of operators have higher priority (precedence) than other ones. For example, we do multiplication and division before addition and subtraction in expressions:

int x = 4 + 3 * 3;
cout << x;
12
int x = 4 + 3 * 3; cout << x;
copy

The program firstly calculates 3 * 3 (multiplication) and then adds 4.

The expressions in the parentheses have higher precedence than other operators and the calculations in them must be executed first.

C++ provides us with a huge number of useful functions for math tasks. Let’s take a look at the more common ones.

The functions max(x, y) and min(x, y) can be used to find the highest and lowest values of x and y respectively:

cout << max(9, 2) << endl;
cout << min(9, 2);
12
cout << max(9, 2) << endl; cout << min(9, 2);
copy
question-icon

Fill the gap:

#include
using namespace std;

int main() {
    int x = 20;
    int y = 30;
    int maximum =
_ _ _
(x, y);
    
_ _ _
_ _ _
maximum;

    return 0;
}
30

Click or drag`n`drop items and fill in the blanks

dots
cout
dots
cin
dots
max
dots
min
dots
>>
dots
maximum
dots
<<

Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 2. Luku 6

Kysy tekoälyä

expand
ChatGPT

Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme

some-alt