A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
pow(base, exponent) computes base raised to the exponent. It handles fractional exponents, negative exponents, and special values like infinity and NaN. It is a general-purpose function that calls into the math library's floating-point unit. For integer exponents, especially small ones like squaring, a simple multiplication is faster and avoids floating-point rounding surprises. pow(x, 2) is not the same as x * x in every edge case.
#include <stdio.h>#include <math.h>int main(void) {printf("pow(2, 10) = %.1f\n", pow(2, 10));printf("pow(9, 0.5) = %.4f\n", pow(9, 0.5));printf("pow(2, -3) = %.6f\n", pow(2, -3));printf("pow(10, 3) = %.1f\n", pow(10, 3));printf("pow(-2, 3) = %.1f\n", pow(-2, 3));printf("pow(-2, 0.5) = %.4f\n", pow(-2, 0.5));return 0;}
pow(-2, 0.5) is the square root of -2, which is not a real number. pow returns NaN. The errno variable is set to EDOM (domain error). If you need complex results, C99's complex.h provides cpow. For real-valued code, check for NaN with isnan() after calling pow with potentially invalid inputs.
#include <stdio.h>#include <math.h>#include <time.h>int main(void) {double x = 3.14159;volatile double r1, r2;clock_t start = clock();for (int i = 0; i < 100000000; i++) {r1 = x * x;}clock_t end = clock();printf("x * x: %.4f s\n", (double)(end - start) / CLOCKS_PER_SEC);start = clock();for (int i = 0; i < 100000000; i++) {r2 = pow(x, 2);}end = clock();printf("pow(x, 2): %.4f s\n", (double)(end - start) / CLOCKS_PER_SEC);return 0;}
The multiplication is nearly a thousand times faster. pow is a general function that handles arbitrary exponents through logarithms and exponentials. For a square, it is massive overkill. Use x * x for squares, x * x * x for cubes. Reserve pow for fractional or large exponents where a loop would be impractical.
pow is the right tool for general exponentiation. For specific small integer powers, multiply directly. The performance difference is enormous and the code is clearer. Next: random number generation, where rand, srand, and their limitations matter for both correctness and security.
Finish the lesson once you have worked through the material. This awards ★ 20 XP.