Содержание
- Неожиданный мусор после еще?
- 3xjakp79a
- Fortran Online Compiler
- Read inputs from stdin
- About Fortran
- Syntax help
- Data Types
- Variables
- Arrays
- Syntax
- Example
- Loops
- 2. Do-While:
- 4. If-Else:
- Ocean Modeling Discussion
- Set a land mask on the sea in SeaGrid
- Set a land mask on the sea in SeaGrid
- Re: Set a land mask on the sea in SeaGrid
- Re: Set a land mask on the sea in SeaGrid
- Re: Set a land mask on the sea in SeaGrid
- Re: Set a land mask on the sea in SeaGrid
- Re: Set a land mask on the sea in SeaGrid
- Re: Set a land mask on the sea in SeaGrid
Неожиданный мусор после еще?
Я новичок в Fortran (я имею в виду, что начал 5 минут назад), и я бездельничал, и я знаю, как делать запуск/завершение программ печати и часть if оператора if. Проблема, с которой я сталкиваюсь, связана с другой частью. Постоянно выдает ошибку:
Для чего нужны скобки после вашего ELSE ? Сообщение об ошибке указывает прямо на них. Я предполагаю, что у вас есть онлайн-руководство по Fortran или его печатная копия, на которую можно ссылаться для правильного синтаксиса.
Сначала я написал это без скобок, но произошла та же ошибка. Я просто смотрел, есть ли разница, но это не так.
Учитывая, что вы начали изучать язык «минуты назад», я бы порекомендовал проверить документацию, а не просто гадать. Вы выучите язык быстрее и точнее. Вы, вероятно, нашли бы ответ быстрее, чем писать здесь.
Правильная структура вашего примера кода должна быть похожа на:
Обратите внимание, что за оператором if в строке 25 следует ключевое слово then, а ваши параметры разделены оператором else.
Также номер строки не нужен. Я просто использовал его здесь, чтобы сослаться на строку в своем ответе.
Здесь не нужны номера строк. Кроме того, постер использует свободную форму, есть ли смысл переходить на фиксированную форму? Я бы также предложил добавить implicit none и объявить x.
я просто использовал номер строки здесь, чтобы я мог сослаться на строку в своем ответе.
@jmh большое спасибо, это сработало! Итак, просто чтобы уточнить, мне нужно «тогда» после моего последнего, если перед тем, как я поставлю «еще»?
да. Вы можете сделать if без «тогда», как в первых двух строках выше, или вы можете сделать то, что известно как конструкция «если-то-иначе», как мы использовали. У вас также может быть if-then-endif без каких-либо других.
Какой редактор кода вы используете? Многие понимают синтаксис фортрана и сделают соответствующие выделения там, где они появляются.
Источник
3xjakp79a
Fortran Online Compiler
Write, Run & Share Fortran code online using OneCompiler’s Fortran online compiler for free. It’s one of the robust, feature-rich online compilers for Fortran language, running on the latest version 7. Getting started with the OneCompiler’s Fortran compiler is simple and pretty fast. The editor shows sample boilerplate code when you choose language as Fortran and start coding.
Read inputs from stdin
OneCompiler’s Fortran online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample Fortran program which takes name as input and prints hello message with your name.
About Fortran
Fortran language was initially developed for scientific calculations by IBM in 1957. It has a number of in-built functions to perform mathematical calculations and is ideal for applications which has more mathematical calculations.
Syntax help
Data Types
Data type | Description | Usage |
---|---|---|
Integer | To store integer variables | integer :: x |
Real | To store float values | real :: x |
Complex | To store complex numbers | complex :: x,y |
Logical | To store boolean values True or false | logical :: x=.True. , logical :: x = .FALSE. |
Character | To store characters and strings | character :: x |
Variables
Variable is a name given to the storage area in order to manipulate them in our programs.
Arrays
Array is a collection of similar data which is stored in continuous memory addresses.
Syntax
Example
Loops
Do is used to execute a set of statement(s) iteratively when a given condition is true and the loop variable must be an integer.
2. Do-While:
Do-While is used to execute a set of statement(s) iteratively when a given condition is true.
If is used to execute a set of statements based on a condition.
4. If-Else:
If is used to execute a set of statements based on a condition and execute another set of statements present in else block, if condition specified in If block fails.
Источник
Ocean Modeling Discussion
Set a land mask on the sea in SeaGrid
Set a land mask on the sea in SeaGrid
#1 Unread post by Scarlett » Wed Feb 07, 2018 5:15 pm
Hi ROMS users!
I’m working with SeaGrid, in my map I want to mask a part of the ocean, like it was a land mask. Already I’m doing it clicking on a each ocean cell where that I want do the mask, but I have many cells (because my resolution is 1/24°) and my masking will be very slow.
I wonder if exist an other method to do the mask in a specific area, if I don’t want to click cell by cell?
Somebody know how? Thanks in advance.
I add my grid, and a select the part that i want to mask.
Re: Set a land mask on the sea in SeaGrid
#2 Unread post by kate » Wed Feb 07, 2018 6:20 pm
Hmm, first, the model requires all angles to be right angles. From what I know of seagrid, your orthogonality errors could be substantial with that grid because you don’t ask it to converge.
The matlab editmask has the capability of changing whole rectangles at a time.
I do this stuff outside matlab. Just figure out the patch I want to change and code it up. This is Python, but you can use your language of comfort (you have one, right. ):
Re: Set a land mask on the sea in SeaGrid
#3 Unread post by Scarlett » Sat Feb 10, 2018 1:04 am
Hi Kate:
So many thanks for your help, I had not known that the model requires all angles to be right angles. I already corrected this, for the other hand I could mask the sea in matlab, based on your code. Thanks.
But I have a question, Do you know how can I save the netcdf file with the new variable (already edited)?
Thanks in advance.
This is my code:
%% Load Netcdf file
ncfile =’/home/ahumada/roms-3.7/matlab/seagrid/GT4_roms_grd.nc’
% nombre de la variable(renglon i:renglon n, columna i: columna n)= O
% cero es tierra
mask_rho(387:432,203:347) = 0
mask_rho(327:432,386:720) = 0
mask_rho(139:327,641:720) = 0
mask_rho(173:326,534:640) = 0
mask_rho(161:180,543:557) = 0
mask_rho(161:174,558:597) = 0
mask_rho(182:326,506:533) = 0
mask_rho(318:326,500:505) = 0
figure(1)
pcolor(lonr, latr,h);
colormap(‘jet’);
hold on
shading interp
Re: Set a land mask on the sea in SeaGrid
#4 Unread post by shchepet » Sun Feb 11, 2018 11:27 am
Re: Set a land mask on the sea in SeaGrid
#5 Unread post by shchepet » Sun Feb 11, 2018 11:53 am
Re: Set a land mask on the sea in SeaGrid
#6 Unread post by Scarlett » Wed Feb 14, 2018 5:46 pm
Hi Alexander F. Shchepetkin:
So many thanks for your help. Yes, it is the kind of grid that I want to create.
I followed your advice to do it with the new tools. But I had have some problems with the mpc compile.
I followed the README.compiling file, but when I compile mpc I get:
mpc.f:335:18: Error: Syntax error in IF-expression at (1)
mpc.f:336:19: Error: Syntax error in IF-expression at (1)
mpc.f:337:20: Error: Syntax error in IF-expression at (1)
mpc.f:338:21: Error: Syntax error in IF-expression at (1)
mpc.f:339:22: Error: Syntax error in IF-expression at (1)
mpc.f:340:23: Error: Syntax error in IF-expression at (1)
mpc.f:343:19:
endif
1
Error: Expecting END PROGRAM statement at (1)
mpc.f:344:18:
endif
1
Error: Expecting END PROGRAM statement at (1)
mpc.f:345:17:
endif
1
Error: Expecting END PROGRAM statement at (1)
mpc.f:346:16:
endif
1
Error: Expecting END PROGRAM statement at (1)
mpc.f:347:15:
endif ! After this moment «i» is
1
Error: Expecting END PROGRAM statement at (1)
mpc.f:348:14:
endif ! index of the last character
1
Error: Expecting END PROGRAM statement at (1)
mpc.f:349:13:
endif ! of Fortran type declaration
1
Error: Expecting END PROGRAM statement at (1)
mpc.f:350:12:
endif ! which may be either «real»,
1
Error: Expecting END PROGRAM statement at (1)
mpc.f:351:11:
endif ! «integer», or «character»..
1
Error: Expecting END PROGRAM statement at (1)
mpc.f:355:10:
do while (j ‘Z’. and.
1
Error: Unexpected junk after ELSE statement at (1)
mpc.f:689:16:
do while(str(m-1) == ‘ ‘)
1
Error: Unclassifiable statement at (1)
mpc.f:693:18:
str(i+2)=str(i)
1
Error: Unclassifiable statement at (1)
mpc.f:695:16:
str(m)=’_’
1
Error: Unclassifiable statement at (1)
mpc.f:696:16:
str(m+1)=’8′
1
Error: Unclassifiable statement at (1)
mpc.f:698:17:
endif
1
Error: Expecting END PROGRAM statement at (1)
mpc.f:699:15:
endif
1
Error: Expecting END PROGRAM statement at (1)
mpc.f:700:13:
endif
1
Error: Expecting END PROGRAM statement at (1)
mpc.f:701:11:
enddo
1
Error: Expecting END PROGRAM statement at (1)
mpc.f:706:17: Error: Syntax error in IF-expression at (1)
mpc.f:707:39:
scratch(i:i)=char(ichar(str(i))+case_fold)
1
Error: Syntax error in argument list at (1)
mpc.f:708:72: Error: Unexpected ELSE statement at (1)
mpc.f:709:12:
scratch(i:i)=str(i)
1
Error: Unclassifiable statement at (1)
mpc.f:710:13:
endif
1
Error: Expecting END DO statement at (1)
mpc.f:794:15: Error: Syntax error in IF-expression at (1)
mpc.f:796:10:
Re: Set a land mask on the sea in SeaGrid
#7 Unread post by shchepet » Wed Feb 14, 2018 11:25 pm
The reason why you have these compiling problems is a faulty version of mpc.F supplied
with the package at some point in the past. This was corrected, but it appears that the
old version came back because at some point the web page was restored from the backup
after disk failure and I did not realize that this happened. At this moment I do not
have access to the web server to replace tar file, so use file «tools.tar» attached to
this response.
Note that a Matlab grid generation tool which was used to make the grid in the previous
post is also available from the same web suite
http://people.atmos.ucla.edu/alex/ROMS/grid_gui.tar
although it is relatively new and lacks instructions — a README file is being written,
but not included into the package yet. It is basically a tool to create analytical
grid using staged conformal transformations. Setting all weird parameters to zero
cent_lat = EWtpr = NStpr = cushn1 = cushn2 = cushn3 = cushn4 = 0
reverts it to easy_grid type of tool: it creates a patch of Mercator grid transferred
to user-specified location and rotated by user-specified azimuth angle.
Optionally the initial rectangular patch on Mercator plane can be deformed into
a desired shape by two kind of transforms:
(i) «tapering» in either direction — rectangle turns into a sector of polar coordinates
with simultaneous exponential stretching along the radial direction (delta r is
proportional to r), and
(ii) «cushioning» — rectangle becomes convex in one direction, concave in the other
(or vice versa, depending whether parameter cushn is positive or negative).
This is actually transform into elliptic coordinates: imagine a family of confocal ellipses
and a family of hyperbolae with the same foci. It can be proven that ellipses and
hyperbolae intersect each other at right angle. This is the basis.
Parameter cushn controls the location of foci:
cushn=0 means that they are infinitely
far away — rectangle remains rectangle and nothing happens;
cushn > 0 makes them approach from infinity along x-axis — actually places the foci
on the horizontal line passing through point (xctr,yctr) and at equal distance from
the point, so the rectangle become concave in eastern and western side (they become
hyperbolae) and convex on northen and southern (they become cutoffs of ellipses).
Now exactly depends on (xctr,yctr).
cushn along y-axis — similarly, but everything is rotated
90 degrees.
It is a bit tricky to control, but after some practice you can fit very weird shapes.
1. The boundaries of the map are determined automatically based on current grid
configuration. Once the desired geographical region is captured unclick the «redraw map»
box on top — this would speed up the drawing by a factor of 100 LITERALLY(!) because
map does not need to be redrawn every time when you hit «update» button.
2. Leaving one of the four boxes, nx, ny, size_x, size_y , blank makes the tool to calculate
the missing value from the condition of isotropy of the grid: dx = dy EVERYWHERE (same
as pm == pn EVERYWHERE). This is very useful. Of course, if size_x, size_y are both
specified, but one of nx,ny is not, then isotropy is not exact because of rounding
to the nearest integer; but is nx,ny are both specified, while one of size_x,size_y left
blank, then isotropy is perfect. THIS IS HOW I ALWAYS RECOMMEND to do it at the end:
at first specify both size_x,size_y, and leave nx blank, play with setting until
you like it, then see Matlab command window to figure nx (the tool always prints the
computed value), put nx into the box, but erase size_x or size_y — the tool will
adjust its value to make the grid be perfectly isotropic.
3. UPDATE button draws the new contour on top of the old (alternating between red and
magenta colors). This is useful to visualize incremental change, so you can accept or
reverse it. Hitting UPDATE button second time without changing any of the parameters
makes single contour.
4. The contours are actually double lines exactly 1dx or 1dy apart from each other.
this is useful because one can use Matlab zoom facility to check how the edge of
the grid is placed relative to the coastline: ideally the coastline should be in
between the double lines — in this case there will be EXACTLY 1 row of mask points.
Источник
You should upgrade or use an alternative browser.
-
Forums
-
Other Sciences
-
Programming and Computer Science
FORTRAN 95 Problem — junk error
- Fortran
-
Thread starter
Diracster -
Start date
Mar 27, 2011
- Mar 27, 2011
- #1
OPEN (10, FILE=’holes.dat’)
DO i=1,x
DO j=1,y
DO k=1,z
IF (s(i,j,k)>0) THEN
EXIT
ELSE IF (k=10) THEN
WRITE (10,*) i, j
END IF
END DO
END DO
END DO
CLOSE (10)
My compiler is giving me the error:
isingmodel8.f95:163.19:
ELSE IF (k=10) THEN
1
Error: Unexpected junk after ELSE statement at (1)
Basically i would like to know why i am getting this error and also if you think that my code will do what i want it to or if there is a better way of doing it. Any help is much appreciated!
Thanks
Answers and Replies
- Mar 27, 2011
- #2
OPEN (10, FILE=’holes.dat’)
DO i=1,x
DO j=1,y
DO k=1,z
IF (s(i,j,k).GT.0) EXIT
IF (k==z) THEN
WRITE (10,*) i, j
END IF
end do
END DO
END DO
CLOSE (10)
Suggested for: FORTRAN 95 Problem — junk error
- Last Post
- Jul 5, 2021
- Last Post
- Jan 18, 2020
- Last Post
- Today, 12:16 AM
- Last Post
- Jan 10, 2023
- Last Post
- Apr 1, 2019
- Last Post
- Aug 27, 2020
- Last Post
- Oct 1, 2022
- Last Post
- Jan 31, 2019
- Last Post
- Jan 31, 2023
- Last Post
- Jun 7, 2018
-
Forums
-
Other Sciences
-
Programming and Computer Science
Description
Sergio Losilla
2014-02-11 13:29:09 UTC
Compiler version: GNU Fortran (Ubuntu 20130917-1ubuntu1) 4.9.0 20130917 (experimental) [trunk revision 202647] Test program: -------------------- program ifelif if (.TRUE.) else if (.FALSE.) end if end program -------------------- Error messages: ---------------------- if.F90:2.15: if (.TRUE.) 1 Error: Cannot assign to a named constant at (1) if.F90:3.11: else if (.FALSE.) 1 Error: Unexpected junk after ELSE statement at (1) [...] ---------------------- Both errors should read something like "Missing THEN after IF/ELSE IF". The first error message doesn't even make sense...
Comment 1
kargl
2014-02-11 14:35:07 UTC
(In reply to Sergio Losilla from comment #0)
> Compiler version:
> GNU Fortran (Ubuntu 20130917-1ubuntu1) 4.9.0 20130917 (experimental) [trunk
> revision 202647]
>
> Test program:
> --------------------
> program ifelif
> if (.TRUE.)
> else if (.FALSE.)
> end if
> end program
> --------------------
>
> Error messages:
> ----------------------
> if.F90:2.15:
>
> if (.TRUE.)
> 1
> Error: Cannot assign to a named constant at (1)
> if.F90:3.11:
>
> else if (.FALSE.)
> 1
> Error: Unexpected junk after ELSE statement at (1)
> [...]
> ----------------------
>
> Both errors should read something like "Missing THEN after IF/ELSE IF".
>
> The first error message doesn't even make sense...
How is the compiler suppose to know that the programmer may have
meant
program ifelif
if (.TRUE.) i = 42
if (.FALSE.) then
j = 42
end if
end program
As for the message that you think makes no sense, I suspect
the parse has identified (.TRUE.) as a malformed expression.
Comment 2
Sergio Losilla
2014-02-11 14:50:18 UTC
(In reply to kargl from comment #1) > How is the compiler suppose to know that the programmer may have > meant > > program ifelif > if (.TRUE.) i = 42 > if (.FALSE.) then > j = 42 > end if > end program As far as I know, there are two possible statements starting with if: if (<expr>) then if (<expr>) <statement> The compiler should recognize that *something* is missing, be it either a then or a statement. > As for the message that you think makes no sense, I suspect > the parse has identified (.TRUE.) as a malformed expression. Well, the message objectively makes no sense because there is no assignment whatsoever. At the very least, the message is confusing.
Comment 3
Dominique d’Humieres
2014-02-11 18:30:59 UTC
Confirmed on 4.7.4, 4.8.3, and trunk (4.9). Related to pr32151.
Comment 4
Dominique d’Humieres
2016-02-25 13:57:56 UTC
*** Bug 38303 has been marked as a duplicate of this bug. ***
Comment 5
Dominique d’Humieres
2019-02-02 19:32:42 UTC
> Error messages: > ---------------------- > if.F90:2.15: > > if (.TRUE.) > 1 > Error: Cannot assign to a named constant at (1) > if.F90:3.11: > > else if (.FALSE.) > 1 > Error: Unexpected junk after ELSE statement at (1) > [...] > ---------------------- > > Both errors should read something like "Missing THEN after IF/ELSE IF". > > The first error message doesn't even make sense... % gfc dec_type_print_red.f90 dec_type_print_red.f90:20:11: 20 | if (b) type*,a(i) ! test TYPE as PRINT inside one-line IF | 1 Error: Cannot assign to a named constant at (1) (from gfortran.dg/dec_type_print.f90 compiled without the -fdec option). IMO replacing "Cannot assign to a named constant" with "Syntax error" will give an immediate clue of what is wrong. A longer alternative could be something such as ""Syntax error, missing or bad STATEMENT".
Comment 6
Dominique d’Humieres
2019-02-19 13:10:55 UTC
I don't understand the goal of the block (line 1651 of gcc/fortran/match.c) /* The gfc_match_assignment() above may have returned a MATCH_NO where the assignment was to a named constant. Check that special case here. */ m = gfc_match_assignment (); if (m == MATCH_NO) { gfc_error ("Cannot assign to a named constant at %C"); gfc_free_expr (expr); gfc_undo_symbols (); gfc_current_locus = old_loc; return MATCH_ERROR; } The closest test matching my understanding of the comment is integer, parameter :: i = 1 if (i == 2) i = 3 ! { dg-error "in variable definition context" } end which gives the following error if_param.f90:2:12: 2 | if (i == 2) i = 3 ! { dg-error "in variable definition context" } | 1 Error: Named constant 'i' in variable definition context (assignment) at (1) If I remove the block, I get the following errors for the test in comment 0: pr60144.f90:2:15: 2 | if (.TRUE.) | 1 Error: Unclassifiable statement in IF-clause at (1) pr60144.f90:3:11: 3 | else if (.FALSE.) | 1 Error: Unexpected junk after ELSE statement at (1) which looks better for the IF statement. For the ELSE IF error, how can I move the caret after '(.FALSE.)' and replace 'junk' with something neutral (token, statement, ...)?
Comment 7
dominiq
2019-05-01 17:40:58 UTC
Author: dominiq Date: Wed May 1 17:40:22 2019 New Revision: 270776 URL: https://gcc.gnu.org/viewcvs?rev=270776&root=gcc&view=rev Log: 2019-05-01 Dominique d'Humieres <dominiq@gcc.gnu.org> PR fortran/60144 * match.c (gfc_match_parens): Change the location for missing ')'. (gfc_match_if): Detect a missing '('. Remove the spurious named constant error. Change the wording of some errors. (gfc_match_else): Change the wording of an error. (gfc_match_elseif): Detect a missing '('. Improve the matching process to get a better syntax analysis. PR fortran/60144 * gfortran.dg/block_name_2.f90: Adjust dg-error. * gfortran.dg/dec_type_print_3.f90.f90: Likewise * gfortran.dg/pr60144.f90: New test. Added: trunk/gcc/testsuite/gfortran.dg/pr60144.f90 Modified: trunk/gcc/fortran/ChangeLog trunk/gcc/fortran/match.c trunk/gcc/testsuite/ChangeLog trunk/gcc/testsuite/gfortran.dg/block_name_2.f90 trunk/gcc/testsuite/gfortran.dg/dec_type_print_3.f90
Comment 8
Dominique d’Humieres
2020-07-30 15:01:33 UTC
This is fixed since at least GCC7.
Я пытаюсь написать программу, которая содержит много других операторов if. Однако я не могу понять, откуда эта ошибка. Любая помощь будет оценена.
Ниже приведен блок if, который у меня сейчас есть:
if (i == 1 .AND. j==1) then
E = E + A(i+1,j) + A(i,j+1) + A(L,j) + A(i,L)
else if (i == 1 .AND. j==L) then
E = E + A(i,j-1) + A(i+1,j) + A(i,1) + A(L,j)
else if (i == L .AND. j == 1) then
E = E + A(i,j+1) + A(i-1,j) + A(1,j) + A(i,L)
else if (i == L .AND. j == L) then
E = E + A(i,j-1) + A(i-1,j) + A(1,j) + A(i,1)
else if (i == 1 .AND. 1 < j < L) then
E = E + A(i+1,j) + A(i,j+1) + A(i,j-1) + A(L,j)
else if (i == L .AND. 1 < j < L) then
E = E + A(i-1,j) + A(i,j+1) + A(i,j-1) + A(1,j)
else if (1 < i < L .AND. j == 1) then
E = E + A(i-1,j) + A(i+1,j) + A(i,j+1) + A(i,L)
else if (1 < i < L .AND. j == L) then
E = E + A(i-1,j) + A(i+1,j) + A(i,j-1) + A(i,1)
else
E = E + A(i-1,j) + A(i+1,j) + A(i,j-1) + A(i,j+1)
end if
Ошибка, которая продолжает появляться:
Ising.f90:56:15:
else if (i == 1 .AND. 1 < j < L) then
1
Error: Unexpected junk after ELSE statement at (1)
Ising.f90:59:15:
else if (i == L .AND. 1 < j < L) then
1
Error: Unexpected junk after ELSE statement at (1)
Ising.f90:62:15:
else if (1 < i < L .AND. j == 1) then
1
Error: Unexpected junk after ELSE statement at (1)
Ising.f90:65:15:
else if (1 < i < L .AND. j == L) then
1
Error: Unexpected junk after ELSE statement at (1)
3 ответа
Лучший ответ
Вы не можете использовать выражения типа 1 < i < L
, чтобы определить, попадает ли i
в диапазон от 1 до L. Вам нужно использовать пересечение двух тестов неравенства. Используйте что-то вроде
else if (1 < i .AND. i < L .AND. j == L) then
1
RussF
3 Мар 2017 в 01:34
Это было бы немного проще для глаз с SELECTED CASE или WHERE и ELSEWHERE. Или создание структуры I if и последующее выполнение J-тестирования внутри нее.
Не видя остальной код, я могу только догадываться, что это может быть похоже на некоторую интерполяцию …
Что-то, где можно было бы сделать это в одной строке математического оператора, если массив был освобожден от (0: n + 1).
-1
Holmz
3 Мар 2017 в 22:38
@VladimirF Ну, как я уже говорил, это похоже на некоторую интерполяцию …
@Ianbush также упомянул несколько хороших моментов.
Может быть … это какой-то сглаживатель / интерполятор?
Более плавный пример:
L = UBOUND(OldThing, 1) !assumes it is square!
ALLOCATE(newthing(0:L+1, 0:L+1) )
DO I = 1, L
DO J = 1, L
NewThing(I,j) = OldThing(I,j)
ENDDO
ENDDO
! Probably a derivative to extrapolate the outliers is better...
! Kindergarten example below is for simplicity.
DO I= 1, L
NewThing(0,(I))= OldThing(1,I)
NewThing(0,(I))= OldThing(1,I)
NewThing(0,(I))= OldThing(1,I)
NewThing(0,(I))= OldThing(1,I)
ENDDO
NewThing(0 , 0) = OldThing(1,1)
NewThing(0, L+1) = OldThing(1,L)
NewThing(L+1, 0) = OldThing(L,1)
NewThing(L+1,L+1) = OldThing(L,L)
!then one is always within the bounds... And the normal case is executed.
E = E + NewThing(I-1,j) + NewThing(i+1,j) + NewThing(i,j-1) + NewThing(i,j+1)
Вероятно, должен произойти возврат NewThing (1: L, 1: L)
0
Holmz
11 Мар 2017 в 13:48
Неожиданный мусор после еще?
Я новичок в Fortran (я имею в виду, что начал 5 минут назад), и я бездельничал, и я знаю, как делать запуск/завершение программ печати и часть if оператора if. Проблема, с которой я сталкиваюсь, связана с другой частью. Постоянно выдает ошибку:
ELSE() print *, "x did not = 1"
1
Error: Unexpected junk after ELSE statement at (1)
Вот мой код:
program hello
x = 1
IF(x==1) print *, "Hello"
IF(x==1) x=2
IF(x==1) print *, "Oh it didnt work..."
ELSE() print *, "x did not = 1 yay it worked"
end program hello
Для чего нужны скобки после вашего ELSE? Сообщение об ошибке указывает прямо на них. Я предполагаю, что у вас есть онлайн-руководство по Fortran или его печатная копия, на которую можно ссылаться для правильного синтаксиса.
— lurker
22.05.2019 13:18
Сначала я написал это без скобок, но произошла та же ошибка. Я просто смотрел, есть ли разница, но это не так.
— user11045164
22.05.2019 13:22
Учитывая, что вы начали изучать язык «минуты назад», я бы порекомендовал проверить документацию, а не просто гадать. Вы выучите язык быстрее и точнее. Вы, вероятно, нашли бы ответ быстрее, чем писать здесь.
— lurker
22.05.2019 13:31
ELSE
является частью блочной конструкции. Таким образом, непосредственно предшествующему оператору if требуется then
после него, а оператор печати идет на отдельной строке. Затем для else, без круглых скобок, оператор печати идет на следующей строке (надеюсь, с отступом, чтобы он выглядел хорошо), а оператор endif
на следующей строке.
— Dan Sp.
22.05.2019 19:52
Ответы
1
Ответ принят как подходящий
Правильная структура вашего примера кода должна быть похожа на:
program hello
x = 1
if ( x == 1) print *, 'hello'
if ( x == 1) x=2
25 if ( x == 1) then
print *, "oh it didn't work..."
else
print *, "x did not = 1 yay it worked"
endif
end program hello
Обратите внимание, что за оператором if в строке 25 следует ключевое слово then, а ваши параметры разделены оператором else.
Также номер строки не нужен. Я просто использовал его здесь, чтобы сослаться на строку в своем ответе.
Здесь не нужны номера строк. Кроме того, постер использует свободную форму, есть ли смысл переходить на фиксированную форму? Я бы также предложил добавить implicit none и объявить x.
— Pierre de Buyl
23.05.2019 11:30
Я просто использовал номер строки здесь, чтобы я мог сослаться на строку в своем ответе.
— Natsfan
23.05.2019 15:23
@jmh большое спасибо, это сработало! Итак, просто чтобы уточнить, мне нужно «тогда» после моего последнего, если перед тем, как я поставлю «еще»?
— user11045164
23.05.2019 15:47
Да. Вы можете сделать if без «тогда», как в первых двух строках выше, или вы можете сделать то, что известно как конструкция «если-то-иначе», как мы использовали. У вас также может быть if-then-endif без каких-либо других.
— Natsfan
23.05.2019 17:53
Какой редактор кода вы используете? Многие понимают синтаксис фортрана и сделают соответствующие выделения там, где они появляются.
— Natsfan
23.05.2019 18:24
Другие вопросы по теме
Fortran Online Compiler
Write, Run & Share Fortran code online using OneCompiler’s Fortran online compiler for free. It’s one of the robust, feature-rich online compilers for Fortran language, running on the latest version 7. Getting started with the OneCompiler’s Fortran compiler is simple and pretty fast. The editor shows sample boilerplate code when you choose language as Fortran
and start coding.
Read inputs from stdin
OneCompiler’s Fortran online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample Fortran program which takes name as input and prints hello message with your name.
program hello
character :: name*30
read *, name
print *, "Hello ", name
end program hello
About Fortran
Fortran language was initially developed for scientific calculations by IBM in 1957. It has a number of in-built functions to perform mathematical calculations and is ideal for applications which has more mathematical calculations.
Syntax help
Data Types
Data type | Description | Usage |
---|---|---|
Integer | To store integer variables | integer :: x |
Real | To store float values | real :: x |
Complex | To store complex numbers | complex :: x,y |
Logical | To store boolean values True or false | logical :: x=.True. , logical :: x = .FALSE. |
Character | To store characters and strings | character :: x |
Variables
Variable is a name given to the storage area in order to manipulate them in our programs.
data type :: variable_name
Arrays
Array is a collection of similar data which is stored in continuous memory addresses.
Syntax
data-type, dimension (x,y) :: array-name
Example
integer, dimension(3,3) :: cube
Loops
1. Do:
Do is used to execute a set of statement(s) iteratively when a given condition is true and the loop variable must be an integer.
do i = start, stop [,step]
! code
end do
2. Do-While:
Do-While is used to execute a set of statement(s) iteratively when a given condition is true.
do while (condition)
!Code
end do
3. If:
If is used to execute a set of statements based on a condition.
if (logical-expression) then
!Code
end if
4. If-Else:
If is used to execute a set of statements based on a condition and execute another set of statements present in else block, if condition specified in If block fails.
if (logical-expression) then
!code when the condition is true
else
!code when the condition fails
end if
5. Case:
Case is similar to switch in C language.
[name:] select case (regular-expression)
case (value1)
! code for value 1
... case (value2)
! code for value 2
...
case default
! default code
...
end select [name]
Hello everyone,
I’m recently seeing this error when running sshuttle on my machine with the nft backend:
Error: syntax error, unexpected junk, expecting end of file or newline or semicolon
add rule inet sshuttle-ipv6-12300 sshuttle-ipv6-12300 ip6 daddr fe80::52e0:39ff:fe5e:a2a4%wlp108s0 udp dport 53 redirect to :12299
Has anyone else encountered this?
Here’s the full command and log:
$ sshuttle --dns -v --method=nft -r USER@HOST
Starting sshuttle proxy (version 1.0.5).
fw: Starting firewall with Python version 3.10.2
fw: ready method name nft.
c : IPv6 enabled: Using default IPv6 listen address ::1
c : Method: nft
c : IPv4: on
c : IPv6: on
c : UDP : off (not available with nft method)
c : DNS : on
c : User: off (not available with nft method)
c : Subnets to forward through remote host (type, IP, cidr mask width, startPort, endPort):
...
c : Subnets to exclude from forwarding:
...
c : DNS requests normally directed at these servers will be redirected to remote:
c : (<AddressFamily.AF_INET: 2>, '192.168.1.1')
c : (<AddressFamily.AF_INET6: 10>, 'fe80::52e0:39ff:fe5e:a2a4%wlp108s0')
c : TCP redirector listening on ('::1', 12300, 0, 0).
c : TCP redirector listening on ('127.0.0.1', 12300).
c : DNS listening on ('::1', 12299, 0, 0).
c : DNS listening on ('127.0.0.1', 12299).
c : Starting client with Python version 3.10.2
c : Connecting to server...
s: Starting server with Python version 3.6.8
s: latency control setting = True
s: auto-nets:False
c : Connected to server.
fw: setting up.
fw: nft add table inet sshuttle-ipv6-12300
fw: nft add chain inet sshuttle-ipv6-12300 prerouting { type nat hook prerouting priority -100; policy accept; }
fw: nft add chain inet sshuttle-ipv6-12300 output { type nat hook output priority -100; policy accept; }
fw: nft add chain inet sshuttle-ipv6-12300 sshuttle-ipv6-12300
fw: nft flush chain inet sshuttle-ipv6-12300 sshuttle-ipv6-12300
fw: nft add rule inet sshuttle-ipv6-12300 output jump sshuttle-ipv6-12300
fw: nft add rule inet sshuttle-ipv6-12300 prerouting jump sshuttle-ipv6-12300
fw: nft add rule inet sshuttle-ipv6-12300 sshuttle-ipv6-12300 meta nfproto != ipv6 return
fw: nft add rule inet sshuttle-ipv6-12300 sshuttle-ipv6-12300 ip6 hoplimit == 63 return
fw: nft add rule inet sshuttle-ipv6-12300 sshuttle-ipv6-12300 ip6 daddr fe80::52e0:39ff:fe5e:a2a4%wlp108s0 udp dport 53 redirect to :12299
Error: syntax error, unexpected junk, expecting end of file or newline or semicolon
add rule inet sshuttle-ipv6-12300 sshuttle-ipv6-12300 ip6 daddr fe80::52e0:39ff:fe5e:a2a4%wlp108s0 udp dport 53 redirect to :12299
^
fw: undoing changes.
fw: nft delete table inet sshuttle-ipv6-12300
fw: nft delete table inet sshuttle-ipv4-12300
Error: Could not process rule: No such file or directory
delete table inet sshuttle-ipv4-12300
^^^^^^^^^^^^^^^^^^^
fw: fw: error: fw: ['nft', 'delete table', 'inet', 'sshuttle-ipv4-12300', ''] returned 1
fw: fatal: fw: ['nft', 'add rule', 'inet', 'sshuttle-ipv6-12300', 'sshuttle-ipv6-12300', 'ip6', 'daddr fe80::52e0:39ff:fe5e:a2a4%wlp108s0', 'udp dport 53', 'redirect to :12299'] returned 1
c : fatal: cleanup: ['/usr/bin/sudo', '-p', '[local sudo] Password: ', '/usr/bin/env', 'PYTHONPATH=/usr/lib/python3.10/site-packages', '/usr/bin/python', '/usr/bin/sshuttle', '-v', '--method', 'nft', '--firewall'] returned 99
These are the various versions I’m using:
$ sshuttle --version
1.0.5
$ python --version
Python 3.10.2
$ nft --version
nftables v1.0.1 (Fearless Fosdick #3)
$ uname -r
5.15.19-1-MANJARO
Any help or tips for debugging are appreciated.