Simple Math
To perform arithmetic operations on variables and values C++ supports the following arithmetic operators:
Let’s try:
9
1
2
3
4
5
int sum = 10 + 3; // 13
int dif = 10 - 3; // 7
int mul = 10 * 3; // 30
int div = 10 / 3; // 3
int mod = 10 % 3; // 1
12345int sum = 10 + 3; // 13 int dif = 10 - 3; // 7 int mul = 10 * 3; // 30 int div = 10 / 3; // 3 int mod = 10 % 3; // 1
By division, any remainder was dropped since we assign the result to the int variable which doesn’t contain any decimals.
You can use all operations above to perform calculations on values, variables, or between variable and value:
9
1
2
3
double a = 32 + 13; // 45
double b = a + 25; // 45 + 25 = 70
double c = a + b; // 70 + 45 = 115
123double a = 32 + 13; // 45 double b = a + 25; // 45 + 25 = 70 double c = a + b; // 70 + 45 = 115
Compito
Swipe to start coding
Robin has 18$ and Ted has 12$. How much money has each of them in average?
- Calculate the sum of their money and assign it to the variable
sum
. - Divide the sum by
2
(number of people) to find the average and assign the result to the variableavr
. - Print the variable
avr
.
Please, don’t forget about semicolon ;
at the end of lines.
Soluzione
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;
int main() {
// Define variables
int moneyOfTed = 12;
int moneyOfRobin = 18;
// Find the sum
int sum = moneyOfTed + moneyOfRobin;
//Find the average
int avr = sum/2;
// Print the result
cout << avr;
return 0;
}
Tutto è chiaro?
Grazie per i tuoi commenti!
Sezione 2. Capitolo 5
single
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;
int main() {
// Define variables
int moneyOfTed = 12;
int moneyOfRobin = 18;
// Find the sum
int sum = _ _ _
//Find the average
int avr = _ _ _
// Print the result
_ _ _
return 0;
}
Chieda ad AI
Chieda ad AI
Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione