Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình C

Chương trình C tính lũy thừa của số cho trước

Nhập hai số nguyên từ người dùng làm cơ số (base) và số mũ (exponent) rồi tính lũy thừa như giải thích dưới đây.

Ví dụ

Xét ví dụ sau để viết chương trình C:

  • Giả sử base = 3
  • Exponent = 4
  • Power = 3*3*3*3

Thuật toán

Theo dõi thuật toán dưới đây:

Bước 1: Khai báo biến int và long. Bước 2: Nhập giá trị base từ console. Bước 3: Nhập giá trị exponent từ console. Bước 4: Vòng lặp While. Exponent != 0         i. value *= base         ii. --exponent Bước 5: In kết quả.

Ví dụ 1 (số nguyên)

Chương trình sau giải thích cách tính lũy thừa số nguyên trong C:

#include  int main(){     int base, exponent;     long value = 1;     printf("Enter a base value:\n ");     scanf("%d", &base);     printf("Enter an exponent value: ");     scanf("%d", &exponent);     while (exponent != 0){         value *= base;         --exponent;     }     printf("result = %ld", value);     return 0; }

Kết quả

Run 1: Enter a base value: 5 Enter an exponent value: 4 result = 625 Run 2: Enter a base value: 8 Enter an exponent value: 3 result = 512

Ví dụ 2 (số thực - dùng pow)

Nếu muốn tìm lũy thừa số thực, dùng hàm pow() định nghĩa sẵn trong math.h.

#include  #include  int main() {     double base, exponent, value;     printf("Enter a base value: ");     scanf("%lf", &base);     printf("Enter an exponent value: ");     scanf("%lf", &exponent);     // tính lũy thừa     value = pow(base, exponent);     printf("%.1lf^%.1lf = %.2lf", base, exponent, value);     return 0; }

Kết quả

Enter a base value: 3.4 Enter an exponent value: 2.3 3.4^2.3 = 16.69