C++ Language
<cmath>
In C++, the '<cmath>' header (or '<math.h>' in C) provides a set of functions for performing mathematical operations. Here's a simple C++ program that find the square root of a given number:
cpp Copy Code
#include<iostream>
#include<cmath>
int main() {
// Input: Get a number from the user
double num;
std::cout << "Enter a number: ";
std::cin >> num;
// Calculate square root using std::sqrt function
if (num >= 0) {
double squRt = std::sqrt(num);
std::cout << "Square root of " << num << " is: " << squRt << std::endl;
} else {
std::cout << "Cannot calculate of a negative number." << std::endl;
}
return 0;
}
Output:
Enter a number: 4 Square root of 4 is: 2
This program prompts the user to enter a number, then it calculates the square root using the 'std::sqrt' function from the '<cmath>' header.
• Some commonly used functions along with examples:
cpp Copy Code
#include<iostream>
#include<cmath>
int main() {
// Basic arithmetic functions
double x = 4.0, y = 2.0;
// Addition
double sum = x + y;
std::cout << "Sum: " << sum << std::endl;
// Subtraction
double difference = x - y;
std::cout << "Difference: " << difference << std::endl;
// Multiplication
double product = x * y;
std::cout << "Product: " << product << std::endl;
// Division
double quotient = x / y;
std::cout << "Quotient: " << quotient << std::endl;
// Exponential and logarithmic functions
double base = 2.0, exponent = 3.0;
// Power function: base^exponent
double powerResult = std::pow(base, exponent);
std::cout << "Power result: " << powerResult << std::endl;
// Square root
double sqrtResult = std::sqrt(x);
std::cout << "Square root of x: " << sqrtResult << std::endl;
// Logarithm to the base 10
double logResult = std::log10(x);
std::cout << "Logarithm base 10 of x: " << logResult << std::endl;
// Trigonometric functions
double angleInRadians = 45.0; // Angles are typically in radians
// Sine
double sinResult = std::sin(angleInRadians);
std::cout << "Sine of " << angleInRadians << " radians: " << sinResult << std::endl;
// Cosine
double cosResult = std::cos(angleInRadians);
std::cout << "Cosine of " << angleInRadians << " radians: " << cosResult << std::endl;
// Tangent
double tanResult = std::tan(angleInRadians);
std::cout << "Tangent of " << angleInRadians << " radians: " << tanResult << std::endl;
return 0;
}
Output:
Sum: 6 Difference: 2 Product: 8 Quotient: 2 Power result: 8 Square root of x: 2 Logarithm base 10 of x: 0.60206 Sine of 45 radians: 0.850904 Cosine of 45 radians: 0.525322 Tangent of 45 radians: 1.61978
This is just a basic example, and there are many more functions available in the '<cmath>' header for various mathematical operations.
What's Next?
We've now entered the finance section on this platform, where you can enhance your financial literacy.