在线编译器 C

#include <stdio.h> #include <string.h> int main() { int a, b; if (scanf("%d %d", &a, &b) != 2) return 0; // 1. 处理特殊情况 0 if (a == 0) { printf("0\n"); return 0; } // 2. 处理正负号 int sign = 1; // 1代表正数,-1代表负数 if (a < 0) { if (b % 2 != 0) { sign = -1; // 负数的奇数次方是负数 } a = -a; // 取绝对值方便后续乘法计算 } // 3. 用数组模拟大数乘法,初始化为 1 int res[100] = {0}; res[0] = 1; int len = 1; // 当前数字的长度 // 循环乘 b 次 for (int i = 0; i < b; i++) { int carry = 0; // 进位 for (int j = 0; j < len; j++) { int prod = res[j] * a + carry; res[j] = prod % 10; // 当前位 carry = prod / 10; // 进位 } // 处理剩下的进位 while (carry > 0) { res[len] = carry % 10; carry /= 10; len++; } } // 4. 开始输出结果 // 如果结果是负数,先打印负号 if (sign == -1) { printf("-"); } // 从最高位开始倒着打印数组 for (int i = len - 1; i >= 0; i--) { printf("%d", res[i]); } printf("\n"); return 0; }
This code computes a raised to the power b (a^b) using integer arithmetic with an array to handle large results. It reads two integers, handles the sign of the result, and performs multiplication digit by digit.

- The array `res` stores digits of the result in reverse order (least significant digit first). After each multiplication by `a`, the code updates each digit and propagates carries. This is correct for positive `a` after taking absolute value.

- The sign handling sets `sign` to -1 only when `a` is negative and `b` is odd. However, note that if `a` is negative and `b` is 0, the result should be 1 (positive), but the code returns early for `a == 0` and does not handle `b == 0` separately. Consider what happens when `a` is negative and `b` is 0.