Practical Code Examples
Basic Mathematical Operations
Trigonometric Functions
#include <stdio.h>
#include <math.h>
int main() {
double angle = M_PI / 4; // 45 degrees
printf("sin(45°) = %f\n", sin(angle));
printf("cos(45°) = %f\n", cos(angle));
return 0;
}
Exponential and Logarithmic Calculations
#include <stdio.h>
#include <math.h>
int main() {
double x = 2.0;
printf("e^%f = %f\n", x, exp(x));
printf("log(%f) = %f\n", x, log(x));
return 0;
}
Complex Mathematical Computations
Quadratic Equation Solver
#include <stdio.h>
#include <math.h>
void solveQuadratic(double a, double b, double c) {
double discriminant = b * b - 4 * a * c;
if (discriminant > 0) {
double root1 = (-b + sqrt(discriminant)) / (2 * a);
double root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("Two real roots: %f and %f\n", root1, root2);
} else if (discriminant == 0) {
double root = -b / (2 * a);
printf("One real root: %f\n", root);
} else {
printf("No real roots\n");
}
}
int main() {
solveQuadratic(1, -5, 6); // x^2 - 5x + 6 = 0
return 0;
}
Statistical Calculations
Standard Deviation Calculation
#include <stdio.h>
#include <math.h>
double calculateStdDeviation(double data[], int size) {
double sum = 0.0, mean, variance = 0.0;
// Calculate mean
for (int i = 0; i < size; i++) {
sum += data[i];
}
mean = sum / size;
// Calculate variance
for (int i = 0; i < size; i++) {
variance += pow(data[i] - mean, 2);
}
variance /= size;
return sqrt(variance);
}
int main() {
double numbers[] = {2, 4, 4, 4, 5, 5, 7, 9};
int size = sizeof(numbers) / sizeof(numbers[0]);
printf("Standard Deviation: %f\n",
calculateStdDeviation(numbers, size));
return 0;
}
Mathematical Function Categories
Category |
Functions |
Use Case |
Trigonometric |
sin(), cos(), tan() |
Angle calculations |
Exponential |
exp(), log() |
Growth/decay models |
Power |
pow(), sqrt() |
Scientific computations |
Rounding |
ceil(), floor() |
Data processing |
Compilation Workflow
graph TD
A[Source Code] --> B[Compile with -lm]
B --> C[Link Math Library]
C --> D[Executable Program]
D --> E[Execute Mathematical Computations]
Error Handling and Precision
Handling Mathematical Errors
#include <stdio.h>
#include <math.h>
#include <errno.h>
int main() {
errno = 0;
double result = sqrt(-1);
if (errno != 0) {
perror("Math error");
}
return 0;
}
LabEx Learning Approach
LabEx provides interactive environments to practice these mathematical programming techniques, allowing developers to experiment and learn through hands-on coding.
Best Practices
- Always include
<math.h>
- Use
-lm
flag during compilation
- Check for potential mathematical errors
- Choose appropriate data types
- Consider computational complexity