Computational Physics - Department of Physics

(Axel Boer) #1

2.1 Getting Started 13


Another feature which is worth noting is that we have skippedexception handlings here.
In chapter 3 we discuss examples that test our input from the command line. But it is easy to
add such a feature, as shown in our modified hello world program


// Hello world code with exception handling
using namespacestd;
#include
#include
#include
intmain (intargc,char*argv[])
{
// Read in output file, abort if there are too few command-line arguments
if( argc <= 1 ){
cout <<"Bad Usage: "<< argv[0] <<
" read also a number on the same line, e.g., prog.exe 0.2"<< endl;
exit(1);// here the program stops.
}
// convert the text argv[1] to double using atof:
doubler = atof(argv[1]);
doubles = sin(r);
cout <<"Hello, World! sin("<< r <<")="<< s << endl;
// success
return0;
}


Here we test that we have more than one argument. If not, the program stops and writes to
screen an error message. Observe also that we have included the mathematics library via the
#include declaration.
To run these programs, you need first to compile and link them in order to obtain an
executable file under operating systems like e.g., UNIX or Linux. Before we proceed we give
therefore examples on how to obtain an executable file under Linux/Unix.
In order to obtain an executable file for a C++ program, the following instructions under
Linux/Unix can be used


c++ -c -Wall myprogram.c
c++ -o myprogram myprogram.o

where the compiler is called through the commandc++. The compiler option -Wall means
that a warning is issued in case of non-standard language. The executable file is in this case
myprogram. The option-cis for compilation only, where the program is translated into ma-
chine code, while the-ooption links the produced object filemyprogram.oand produces the
executablemyprogram.
The corresponding Fortran code is


http://folk.uio.no/mhjensen/compphys/programs/chapter02/Fortran/program1.f90
PROGRAMshw
IMPLICIT NONE
REAL(KIND=8) :: r! Input number
REAL(KIND=8) :: s! Result


! Get a number from user
WRITE(,)'Input a number: '
READ(,) r
! Calculate the sine of the number
s = SIN(r)
! Write result to screen

Free download pdf