Writing Mathematical Expressions and Operators in C++
Topics to be covered:
Writing to the console and formatting output in C++
Understanding operator precedence and using parentheses
Best practices in C++: avoiding magic numbers with constants
Working with numbers in C++: understanding narrowing conversions
1. Writing to the console and formatting output in C++
In C++, we can write to the console using the std::cout stream. To format the output, we can use
the << operator to insert formatting flags, such as std::endl for a new line and std::setw() for width.
Example code:
#include <iostream>
int main() {
std::cout << "Hello, world!" << std::endl;
std::cout << std::setw(10) << 5;
}
2. Understanding operator precedence and using parentheses
When writing mathematical expressions in C++, it is important to understand operator precedence.
For example, multiplication and division operations are performed before addition and subtraction
operations. Parentheses can be used to override this order.
Example code:
#include <iostream>
int main() {
std::cout << 2 + 2 * 3 << std::endl; // Outputs: 8
std::cout << (2 + 2) * 3 << std::endl; // Outputs: 12
}
3. Best practices in C++: avoiding magic numbers with constants
Topics to be covered:
Writing to the console and formatting output in C++
Understanding operator precedence and using parentheses
Best practices in C++: avoiding magic numbers with constants
Working with numbers in C++: understanding narrowing conversions
1. Writing to the console and formatting output in C++
In C++, we can write to the console using the std::cout stream. To format the output, we can use
the << operator to insert formatting flags, such as std::endl for a new line and std::setw() for width.
Example code:
#include <iostream>
int main() {
std::cout << "Hello, world!" << std::endl;
std::cout << std::setw(10) << 5;
}
2. Understanding operator precedence and using parentheses
When writing mathematical expressions in C++, it is important to understand operator precedence.
For example, multiplication and division operations are performed before addition and subtraction
operations. Parentheses can be used to override this order.
Example code:
#include <iostream>
int main() {
std::cout << 2 + 2 * 3 << std::endl; // Outputs: 8
std::cout << (2 + 2) * 3 << std::endl; // Outputs: 12
}
3. Best practices in C++: avoiding magic numbers with constants