gpt4 book ai didi

algorithm - Fortran 算法帮助 - 得到错误的结果

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:11:41 32 4
gpt4 key购买 nike

我目前正在研究 Fortran 矩阵计算器。我正在编译程序,它似乎可以正常工作,但我没有收到正确的结果。当我选择加法特征时,我的程序在两个矩阵中接受并将它们加在一起。我的结果似乎是错误的。例如,如果我选择两个大小为 2x2 且列表为 1 的矩阵作为每个条目,我会收到 3、3、3 的加法结果。我不知道算法哪里出了问题。我还没有检查其他算法,因为我试图一次修复一个算法。下面是我的代码

  *START PROGRAM
PROGRAM MAIN

*DECLARATIONS
INTEGER SELECTION, DONE, VALID, J, I, K, M, N
INTEGER, DIMENSION(10,10):: SUM, A, B

*INTITIALIZE
M = 0
N = 0
J = 0
I = 0
K = 0
DONE = 1
VALID = 1

*LOOP UNTIL USER CHOOSES TO QUIT

DO WHILE(DONE .GT. 0)

*DISPLAY MENU UNTIL VALID ENTRY IS ENTERED

DO WHILE (VALID .GT. 0)
*PRINT MENU
PRINT *,'MATRIX CALCULATOR'
PRINT *,'PLEASE MAKE A SELECTION'
PRINT *,'1) MATRIX ADDITION'
PRINT *,'2) MATRIX SUBTRACTION'
PRINT *,'3) MATRIX MULTIPLICATION'
PRINT *,'4) MATRIX TRANSPOSE'
PRINT *,'5) QUIT PROGRAM'
READ (*,*) SELECTION

*VALID ENTRY CHECK
IF (SELECTION .GT. 5 .OR. SELECTION .LT. 1) THEN
PRINT *,'PLEASE ENTER A VALID SELECTION'
ELSE
VALID= -1
END IF

*END WHEN VALID ENTRY IS ENTERED
END DO

*QUIT?
IF (SELECTION .EQ. 5) THEN
DONE = -1
ELSE
*OTHERWISE CONTINUE
*GET DIMENTIONS INPUT
PRINT *,'PLEASE ENTER THE DIMENTIONS'
PRINT *,'ENTER IN M:'
READ (*,*) M
PRINT *,'ENTER IN N:'
READ (*,*) N
*GET IN MATRIX
PRINT *, 'PLEASE ENTER IN MATRIX A'
DO J=1, M
DO I=1, N
PRINT *, 'ENTER IN VALUE I, I', J, I
READ(*,*) A(M,N)
END DO
END DO

PRINT *, 'PLEASE ENTER IN MATRIX B'
DO J=1, M
DO I=1, N
PRINT *, 'ENTER IN VALUE I, I', J,I
READ(*,*) B(M,N)
END DO
END DO

*PERFORM DESIRED CALCULATION
SELECT CASE(SELECTION)
*CASE 1
CASE (1)
PRINT *,'MATRIX ADDITION'
DO J=1,M
DO I=1,N
SUM(J,I)=A(J,I)+B(J,I)
END DO
END DO

*PRINT ADDITION RESULT
PRINT *,'ADDITION RESULT'
DO J=1, M
DO I=1, N
WRITE (*,*) SUM(J,I)
END DO
END DO
*CASE 2
CASE (2)
PRINT *,'MATRIX SUBTRACTION'
DO J=1,M
DO I=1,N
SUM(J,I)=A(J,I)-B(J,I)
END DO
END DO

*PRINT SUBTRACTION RESULT
PRINT *,'SUBTRACTION RESULT'
DO J=1, M
DO I=1, N
WRITE (*,*) SUM(J,I)
END DO
END DO
*CASE 3
CASE (3)
PRINT *,'MATRIX MULTIPLICATION'
DO J=1, M
DO I=1, N
DO K=1, N
SUM(J,I) = SUM(J,I)+A(J,K)*B(I,J)
END DO
END DO
END DO

*PRINT MULTIPLICATION RESULT
DO J=1, M
DO I=1, N
WRITE (*,*) SUM(J,I)
END DO
END DO
*CASE 4
CASE (4)
PRINT *,'MATRIX TRANSPOSE'
DO J=1, M
DO I=1, N
B(I,J) = A(J,I)
END DO
END DO
*PRINT TRANSPOSE RESULT
PRINT *, 'MATRIX A RESULT'
DO J=1, M
DO I=1, N
WRITE (*,*) A(J,I)
END DO
END DO
PRINT *, 'MATRIX B RESULT'
DO J=1, M
DO I=1, N
WRITE (*,*) B(J,I)
END DO
END DO
CASE DEFAULT
PRINT *,'SOMETHING HAS GONE WRONG'
END SELECT

*USER SELECTED TO QUIT
END IF
END DO
PRINT *, 'PROGRAM HAS ENDED'
*END PROGRAM
STOP
END

最佳答案

避免所犯错误的一种方法是使用 Fortran 的数组函数。例如,如果数组 A 和 B 的大小相同,您可以使用单个语句对数组 A 和 B 求和:

C = A + B

您还可以使用内部过程 matmultranspose 分别进行矩阵乘法和转置。

关于algorithm - Fortran 算法帮助 - 得到错误的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9763967/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com