Menghitung Deret 1-1/2+1/3-1/4+..+1/n

Analysis program:
This is a program iteraktif to find the sum of the input sequence (n). Please try running.

Program :

#include <iostream.h>
#include<conio.h>

class hitung
{
public:
       void input();
       int proses();
private:
        int n;
        float rumus,jumlah,total;
        };

void hitung::input(){
cin>>n;
cout<<endl;}

int hitung::proses(){
jumlah=0;
total=0;
rumus=-1;
for(int j=1; j<=n; j++){
rumus=(rumus*(-1));
total=rumus/j;
jumlah+=total;
if(j==1)
cout<<"("<<total<<")";
if(j>1)
cout<<"+("<<total<<")";
}

cout<<endl<<endl<<"hasil penjumlahan deret = "<<jumlah;
return jumlah;
}

int main()
{
cout<<"menghitung jumlah dari rumus 1-(1/2)+(1/3)-(1/4)+...+(1/n)"<<endl<<endl;
cout<<"nilai n : ";
hitung deret;
deret.input();
deret.proses();

getch();
return 0;
} 


Jeliotnya :

import jeliot.io.*;

public class MyClass {
    
    public static double iteratif(double x){
        double jumlah=0.0;
        for(int i=1; i<=x; i++){
            if(i % 2 == 0) jumlah=jumlah-1.0/i;
            else jumlah=jumlah+1.0/i;
        }
        return jumlah;
    }
    
    public static double rekursif(double x){
        double jumlah=0.0;
        if(x==1) return 1;
        else     if(x % 2 == 0) jumlah= -1.0/x + rekursif(x-1);
                else jumlah= 1.0/x + rekursif(x-1);
           return jumlah;
    }
    
    public static void main() {
    double x;
    
    MyClass a = new MyClass();
    System.out.print("Masukkan batas bilangan : ");
    x=Input.readDouble();
    System.out.println("Hasil iteratif : " + iteratif(x));
    System.out.print("Hasil rekursif : " + rekursif(x));
    
   }
}

Posted on April 22, 2011, in Alprog. Bookmark the permalink. Tinggalkan komentar.

Tinggalkan Balasan

Isikan data di bawah atau klik salah satu ikon untuk log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout /  Ubah )

Foto Google+

You are commenting using your Google+ account. Logout /  Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout /  Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout /  Ubah )

Connecting to %s

%d blogger menyukai ini: