What would be the conversion of following C++ logical operator into Fortran 90 (.f90)? If ( vx
is present or vy
is present). Here vx
and vy
are components of velocity
if(vx || vy){
vT=sqrt(vx*vx + vy*vy);
}
I have tried following
if(vx .or. vy) then
vT = sqrt(vx*vx + vy*vy)
end if
but I am getting error:
operands of logical operator `.or.` at (1) are REAL(8)/REAL(8).
Can anyone guide me here?
The C++ version is implicitly comparing vx
and vy
with zero.
In Fortran, you have to do so explicitly 1 :
if (vx /= 0 .or. vy /= 0) then
Since the if
statement looks like a performance optimization, it might be worth questioning whether it's needed altogether or could be replaced with an unconditional assignment to vT
(that would set vT
to zero if both vx
and vy
are zero).
1 I hope I got this right; haven't programmed in Fortran for many years.
In the present case it is not relevant, but in general it should be noted that Fortran logical operations are not short-circuited. So, for example, the following C++ code
if (a == 0 || 10 / a == 1)
{
...
}
is not equivalent to
if (a == 0 .or. 10 / a == 1) then
...
end if
in Fortran. A compiler may decide to evaluate the second term first and then... oops. It should be written using two nested if
s.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.