문제

I'm trying to create pascal triangle with FORTRAN. I did the algorithm. Compiled in C and succeeded but for some reason I'm not getting the same desired result in FORTRAN. Can anyone help me out in this one?

Code in C (Working):

#include <stdio.h>
#include <stdlib.h>

int main()
{
  unsigned int c, i, j, k,n;
  scanf("%d",&n);

  for(i=0; i < n; i++) {
    c = 1;
    for(j=1; j <= (n-1-i); j++) printf(" ");
    for(k=0; k <= i; k++) {
      printf("%2d", c);
      c = c * (i-k)/(k+1);
    }
    printf("\n");

  }
  return 0;
}

Code in FORTRAN (Not Working, Need help here):

program pascal
  implicit none
  integer i,j,k,p,n
  read(*,*)n
  i=0
  do while(i.lt.n)
    p=1
    do j=1,n-1-i
    write(*,5)
    5 format(1x)
    enddo
    do k = 0,i
    write(*,1)p
    1 format(i2)
    p = p*(i-k)/(k+1)
    enddo
    i=i+1
    write(*,2)
    2 format(/)
    enddo
endprogram
도움이 되었습니까?

해결책 2

You can try this. Notice that if you enter a number n > 9, it will not work (and for n > 5, it's not that pretty).

program pascal
    implicit none
    integer :: i, j, n, c
    read(*, *) n
    do i = 0, n - 1
        c = 1
        do j = 0, n - i
            write(*, "(' ')", advance="no")
        end do
        do j = 0, i
            write(*, "(I2)", advance="no") c
            c = (c * (i - j)) / (j + 1)
        end do
        write(*, *)
    end do
end program

In your program, almost everything is right, except when you print : Fortran add always a new line if you don't add the optional advance="no".

Regarding style, it's not very useful here to put formats in a separate line, and .lt. can be replaced by < in Fortran 90. Also, your indentation is not correct in the inner loops.

다른 팁

Here are some improvements that can handle larger values of n:

program pascal
implicit none
integer i,j,k,p,n
write (*, '("input n: ")', advance="no")
read(*,*) n
do i=0,n-1
   p=1
   do j=1,n-1-i
      write(*,'(3X)', advance="no")
   enddo
   do k = 0,i
      write(*,'(I6)', advance="no") p
      p = p*(i-k)/(k+1)
   enddo
   write(*, '(/)')
enddo
endprogram

The formatted IO for this program seems simple to me. More complicated if you wanted to figure out the largest integer that will be output for a particular value of n and output the most compact triangle for that case...

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top