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;
}
Advanced Calculation Scenarios
Exponential and Logarithmic Calculations
#include <stdio.h>
#include <math.h>
int main() {
double base = 2.0;
double exponent = 3.0;
printf("Power calculation: %.2f\n", pow(base, exponent));
printf("Natural logarithm: %.2f\n", log(base));
printf("Base 10 logarithm: %.2f\n", log10(base));
return 0;
}
Rounding and Absolute Value
Precision Manipulation
#include <stdio.h>
#include <math.h>
int main() {
double numbers[] = {-3.7, 2.3, 4.5, -1.2};
for (int i = 0; i < 4; i++) {
printf("Original: %.2f\n", numbers[i]);
printf("Ceiling: %.2f\n", ceil(numbers[i]));
printf("Floor: %.2f\n", floor(numbers[i]));
printf("Absolute: %.2f\n\n", fabs(numbers[i]));
}
return 0;
}
Mathematical Function Categories
Category |
Functions |
Purpose |
Trigonometric |
sin(), cos(), tan() |
Angle calculations |
Exponential |
exp(), log(), pow() |
Exponential operations |
Rounding |
ceil(), floor(), round() |
Number precision |
Comparison |
fmax(), fmin() |
Numerical comparisons |
Complex Mathematical Scenarios
Statistical Calculations
#include <stdio.h>
#include <math.h>
double calculate_standard_deviation(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 data[] = {2, 4, 4, 4, 5, 5, 7, 9};
int size = sizeof(data) / sizeof(data[0]);
printf("Standard Deviation: %.2f\n",
calculate_standard_deviation(data, size));
return 0;
}
Compilation Workflow
graph LR
A[Source Code] --> B[Compile with -lm]
B --> C[Link Math Library]
C --> D[Executable Program]
LabEx Learning Tip
When practicing these examples, LabEx recommends experimenting with different input values and understanding how mathematical functions behave.
Error Handling Considerations
- Check return values of mathematical functions
- Handle potential domain and range errors
- Use
isnan()
and isinf()
for special value detection