Yêu cầu:
– Nhập vào số nguyên dương n
– Tính tổng S(x, n) = x + x^3 + x^5 +…+ x^(2n+1)
Giải thuật:
– Dùng vòng lặp for, do while để duyệt biến i từ 0 tới n
– Tính tổng: s = s + x^(2*i + 1)
– Dùng hàm pow để tính x^(2*i + 1)
Code
/************************************************************ * Author: VNCODING * History * 2016/12/14 first create VNCODING *************************************************************/ #include <stdio.h> #include <conio.h> #include <math.h> int main() { printf("S(x, n) = x + x^3 + x^5 +…+ x^(2n+1)\n"); int i, n; float x; float s = 0.0; printf("x = "); scanf("%f", &x); do { printf("n = "); scanf("%d", &n); }while(n < 0); for(i = 0; i <= n; i++) { s += pow(double(x), double(2*i + 1)); } printf("\nS(%d) = %f", n, s); getch(); return 0; }
Kết quả:
em van không hiểu vì sao lại định dạng theo float mà không phải là int.
@sstrrikerr, đây là tổng vô hạn tuần hoàn thì sao ra kết quả là int được