Sei sulla pagina 1di 5

Program to do decimal to binary conversion in fortran- main.f95 and dec2bin.

f95

program name use dec2bin implicit none integer :: response,binary,input,bdec,adec real :: binaradix

print*,'Choose one option:' print*,'1.Convert a positive integer to binary' print*,'2.Convert a positive real number to binary' read*,response

if (response==1) then print*,'Enter the integer:' read*,input binary=dec2binInt(input) print*,binary else if (response==2) then print*,'Enter the part before float as integer:' read*,bdec print*,'Enter the part after the decimal as integer:' read*,adec binary=dec2binInt(bdec) print*,'The part before binary radix:'

print*,binary binaradix=dec2binFlt(adec) print*,'The part after binary radix:' print*, binaradix end if end program name

module dec2bin

contains

integer function lenInt(input) implicit none integer :: input integer ::rem,num,count

count=0 num=input do while(num/=0) rem=mod(num,10) num=(num-rem)/10 count=count+1 end do

lenInt=count end function lenInt

integer function dec2binInt(input)

implicit none integer :: input,output integer :: quo,rem,num,counter=0,index,Palindrome

num=input quo=1 output=0

!Find binary digits in reverse do while(quo/=0) quo=num/2 rem=num-(quo*2) num=quo output=(output*10)+rem counter=counter+1 end do

!Palindrome of the output Palindrome=0 do index=1,counter

rem=mod(output,10) Palindrome=(Palindrome*10)+rem output=(output-rem)/10 end do

!Send the palindrome out dec2binInt=Palindrome

end function

real function dec2binFlt(input)

implicit none integer :: input integer :: count,prod,num,length,lenTemp real :: temp num=input temp=0.1 count=0 do while(count<21 .and. num>0) length= lenInt(num) prod=num*2 lenTemp= lenInt(prod)

if (lenTemp>length) then

temp=(temp/10.0)+0.1 num=mod(prod,10**(lenTemp-1)) count=count+1 else temp=temp/10.0 count=count+1 num=prod end if end do

dec2binFlt=temp

end function end module dec2bin

Potrebbero piacerti anche