Tính tổng S(n) = 1/2 + 1/4 + 1/6 + 1/8 + 1/2n

Yêu cầu:
– Nhập vào số nguyên dương n
– Tính tổng s(n) = 1/2 + 1/4 + 1/6 + 1/8 + … + 1/2n

Giải thuật:
– Dùng vòng lặp for, do while để duyệt biến i từ 1 tới n
– Tính tổng: s = s + 1/(2*i)

Code:

/************************************************************
* Author: VNCODING
* History
* 2016/12/12        first create    VNCODING
*************************************************************/

#include <stdio.h>
#include <conio.h>

int main()
{
	printf("S(n) = 1/2 + 1/4 + 1/6 + 1/8 + 1/2n\n");
	int i, n;
    float s = 0.0;
	do
	{
		printf("n = ");
		scanf("%d", &n);
	}while(n <= 0);
	
	for(i = 1; i <= n; i++)
	{
        s += 1.0/(2*i);
	}
	printf("\nS(%d) = %f", n, s);
	getch();
	return 0;
}

Kết quả:

Tính tổng S(n) = 1/2 + 1/4 + 1/6 + 1/8 + 1/2n
Tính tổng S(n) = 1/2 + 1/4 + 1/6 + 1/8 + 1/2n

5 Comments on Tính tổng S(n) = 1/2 + 1/4 + 1/6 + 1/8 + 1/2n

  1. sao của em nó không ra kết quả nó cứ hỏi n mặc dù em bấm r xog lại hỏi tiếp em sai chỗ nào ạ
    #include
    #include
    int main()
    {
    printf(“S(n)=1/2+1/4+1/8+1/2n\n”);
    int n,i;
    float S=0.0;
    do
    {
    printf(“\nnhap n:”);
    scanf(“%d,&n”);
    } while(n<=0);
    for(i=1;i<=n;i++)
    {
    S+=1.0/(2*i);
    }
    printf("\n S(%d)=%f",S,n);
    getch();
    return 0;
    }

Leave a Reply to Lam Cancel reply