gpt4 book ai didi

fortran - 求解二次方程但得到奇怪的错误

转载 作者:行者123 更新时间:2023-12-02 00:40:55 25 4
gpt4 key购买 nike

我正在尝试用 Fortran 编写我的第一个程序,尝试求解二次方程。我对我的代码进行了两次和三次检查,没有发现任何错误。我在不同位置不断收到“(1) 处名称中的无效字符”和“(1) 处无法分类的语句”。代码有什么问题?

! This program solves quadratic equations
! of the form ax^2 + bx + c = 0.
! Record:
! Name: Date: Notes:
! Damon Robles 4/3/10 Original Code

PROGRAM quad_solv
IMPLICIT NONE

! Variables
REAL :: a, b, c
REAL :: discrim, root1, root2,
COMPLEX :: comp1, comp2
CHARACTER(len=1) :: correct

! Prompt user for coefficients.
WRITE(*,*) "This program solves quadratic equations "
WRITE(*,*) "of the form ax^2 + bx + c = 0. "
WRITE(*,*) "Please enter the coefficients a, b, and "
WRITE(*,*) "c, separated by commas:"
READ(*,*) a, b, c
WRITE(*,*) "Is this correct: a = ", a, " b = ", b
WRITE(*,*) " c = ", c, " [Y/N]? "
READ(*,*) correct
IF correct = N STOP
IF correct = Y THEN

! Definition
discrim = b**2 - 4*a*c

! Calculations
IF discrim > 0 THEN
root1 = (-b + sqrt(discrim))/(2*a)
root2 = (-b - sqrt(discrim))/(2*a)
WRITE(*,*) "This equation has two real roots. "
WRITE(*,*) "x1 = ", root1
WRITE(*,*) "x2 = ", root2
IF discrim = 0 THEN
root1 = -b/(2*a)
WRITE(*,*) "This equation has a double root. "
WRITE(*,*) "x1 = ", root1
IF discrim < 0 THEN
comp1 = (-b + sqrt(discrim))/(2*a)
comp2 = (-b - sqrt(discrim))/(2*a)
WRITE(*,*) "x1 = ", comp1
WRITE(*,*) "x2 = ", comp2

PROGRAM END quad_solv

最佳答案

关于如何循环回到重做输入的附加问题 -- 一个演示 Fortran >= 90 循环特性的示例程序。循环显然是无限的 -- exit 由 IF 语句控制退出循环并使循环有限。还显示了 cycle 控件,它在遇到无效输入时使用,否则会使程序崩溃。 (例如,键入“A”作为第一次读取的输入,而不是数字。)在这种情况下,iostat 变量获取一个非零值,IF 语句激活循环,​​DO 循环的其余部分是跳过,以便循环重新循环。

program test_readdata

real :: a, b, c
integer :: ReturnCode
character (len=1) :: correct

ReadData: do

write (*, '( "This program solves quadratic equations of the form ax^2 + bx + c = 0. " )' )
write (*, '( "Please enter the coefficients a, b, and c, separated by commas: " )', advance='no' )
read (*,*, iostat=ReturnCode) a, b, c
if ( ReturnCode /= 0 ) cycle ReadData
write (*,*) "Is this correct: a = ", a, " b = ", b, " c = ", c
write (*, '( "Enter Y or N: " )', advance='no' )
read (*,*, iostat=ReturnCode) correct
if ( ReturnCode /= 0 ) cycle ReadData
if ( correct == 'Y' .or. correct == 'y' ) exit ReadData

end do ReadData

stop

end program test_readdata

我推荐的书:Fortran 95/2003 explained 作者:Metcalf、Reid 和 Cohen。

关于fortran - 求解二次方程但得到奇怪的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2588081/

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