Вы находитесь на странице: 1из 31

Introduction to C++

Introduction to C++

Dr Alex Martin 2013

Lecture Set 4 Slide 1

Casts and type Conversions

We have already seen that in so e circu stances the C++ co !iler auto atically converts a varia"le or constant o# one ty!e e$%$ int to another e$%$ dou"le$ Consider the code&

double x=2; ... double y = x * 3/4;

'his results in y "ein% assi%ned the value 1$( des!ite the a!!arent inte%er division$ 'his is "ecause the ulti!lication is done #irst and there an i !licit conversion o# the inte%er )3) to a #loatin% !oint *uantity$ +$,$ i# one -rote y . 3/4 0 x1 the value assi%ned -ould "e 0$$$"ecause the inte%er division -ould "e done #irst$

Introduction to C++

Dr Alex Martin 2013

Lecture Set 4 Slide 2

Casts and type Conversions

So eti es it is use#ul to a2e this conversion "et-een ty!es ex!licit$ 'his is done usin% the castin% o!erators$ 'hese are unitary o!erators -hich ta2e t-o #or s& ( type ) expression type ( expression ) -here ty!e is one o# the "uilt3in ty!es4 int 4 dou"le etc$ 'he #irst o# the #or s is the tradition 5C5 -ay o# doin% casts4 -hilst the second -as introduced -ith C++

Introduction to C++

Dr Alex Martin 2013

Lecture Set 4 Slide 3

Casts and type Conversions


'he exa !le !ro%ra #ra% ent& double a = double b = double c = casts$c!! de onstrates the use o# casts$ In the code 3/4; (double)3/4; double(3)/4;

a -ill "e assi%ned the value 0 "ecause o# inte%er division$ ,ut "oth " and c -ill "e assi%ned the value 0$6( "ecause o# the ex!licit conversion o# the constant 3 to a dou"le$ In the second #ra% ent& double p = (int)M_PI; double q = int(M_PI); ,oth ! and * -ill "e assi%ned the value 3$0 "ecause the value o# !i -ill "e converted to an int 7and hence truncated8 "e#ore "ein% converted "ac2 to a dou"le -hen assi%ned to the le#t3hand3side o# the ex!ression$

Introduction to C++

Dr Alex Martin 2013

Lecture Set 4 Slide 4

References

We have no- discussed and -ritten several si !le #unctions$ 9o-ever4 consider ho- one i%ht -rite a #unction to s-a! the values held in t-o varia"les$ +aively one -ould declare and de#ine such a #unction in the #ollo-in% -ay& void !ap(int a"int b); ... ... void !ap(int a" int b)# int t$p=a; a=b; b=t$p; %

Introduction to C++

Dr Alex Martin 2013

Lecture Set 4 Slide (

References
As you ay veri#y usin% the !ro%ra s-a!$c!!$ 'his doesn5t -or2 as ex!ected;

'he reason #or this is that in C++ 7and C8 all in!ut varia"les are4 "y de#ault4 !assed3"y3value 'his eans that -hen a #unction is used4 te !orary4 co!ies o# the in!ut ar%u ents are ade 7on the stac28$ I# a varia"le5s contents are odi#ied -ithin the #unction4 only the te !orary co!y is a##ected$ 'his causes a !ro"le i# one -ishes to -rite a #unction -hich returns ore than the one nor al return value$ 'he -ay around this is to use re#erences or !ointers$

Introduction to C++

Dr Alex Martin 2013

Lecture Set 4 Slide :

References

Reference Types A re#erence is an alias #or another varia"le$ <ne creates a re#erence "y declarin% a varia"le o# the sa e ty!e as the varia"le one -ishes to re#erence #ollo-ed "y the re#erence o!erator4 =4 e$%$ int i=2&; int' ( = i;

Introduction to C++

Dr Alex Martin 2013

Lecture Set 4 Slide 6

References
+$,$ -hen a re#erence is created4 e$%$ declared4 it M?S' "e associated -ith a varia"le 7o# the correct ty!e84 and this association can5t "e chan%ed later in the !ro%ra $ 'his association can "e illustrated as #ollo-s&

<nce a re#erence is created4 it is used @ust li2e any other varia"le$ 9o-ever4 any odi#ication e$%$ assi%n ent to the re#erence actually odi#ies the e ory location associated -ith the varia"le the re#erence re#ers to$ 'his is de onstrated in the exa !le !ro%ra re#$c!!$
Introduction to C++ Dr Alex Martin 2013 Lecture Set 4 Slide >

References
Using references as function input arguments
<ne o# the ain use #or re#erences is to allo- #unctions -hich can odi#y their in!ut ar%u ents$ I# instead o# s!eci#yin% a #unction5s ar%u ents as "ein% o# a nor al ty!e4 one s!eci#ies a re#erence to that ty!e i$e$ "y si !ly addin% an =4 the ar%u ents are !assed3"y3re#erence$ When the #unction is called re#erences are created -hich re#er to the varia"les used as ar%u ents to the #unction$ 'his eans that any odi#ications to these ar%u ents -ithin the #unction are actually ade to the ori%inal varia"les; 'his is de onstrated in a -or2in% version o# the s-a! !ro%ra &

Introduction to C++

Dr Alex Martin 2013

Lecture Set 4 Slide A

References

void !ap(int' a" int' b); ... ... void !ap(int' a" int' b)# int t$p=a; a=b; b=t$p; % Bou ay veri#y usin% the !ro%ra $ s-a!r$c!! -or2s as it should$

Introduction to C++

Dr Alex Martin 2013

Lecture Set 4 Slide 10

Using Random numbers

So e al%orith s and techni*ues concerned -ith odellin% and si ulations re*uire the use o# rando nu "ers$ ?sually #or scienti#ic !ur!oses4 -hen rando nu "ers are re*uired4 -e actually utiliCe an al%orith -hich !roduce a see in% rando se*uence o# nu "ers$ 'hese Dseudo3Eando nu "ers are +<' truly rando 4 i# the #unction i !le entin% the al%orith is called -ith the sa e in!ut !ara eters4 the sa e se*uence o# nu "ers -ill al-ays "e !roduced$ Most rando nu "er %eneratin% #unctions are initialiCed "y callin% a s!ecial #unction -ith an initial Seed value once at the "e%innin% o# a !ro%ra $

Introduction to C++

Dr Alex Martin 2013

Lecture Set 4 Slide 11

Using Random numbers

'he "asic #unctions to use rando nu "ers are de#ined the the header #ile Fcstdli"G$ 'here are t-o #unctions o# interest& void )and(un i*ned eed); nu "ers$

sets its ar%u ent as the seed #or a ne- se*uence o# !seudo3rando Hor exa !le )and(+234,); sets the seed to "e 1234(

Introduction to C++

Dr Alex Martin 2013

Lecture Set 4 Slide 12

Using Random numbers

A second #unction& int )and(); returns a !seudo3rando inte%er "et-een 0 and EA+DIMAJ

I !ortantly the se*uence o# rando nu "ers returned "y rand78 is re!eata"le "y callin% srand78 -ith the sa e seed value$ I# no seed value is !rovided4 the rand78 #unction is auto atically seeded -ith a value o# 1$ So i# the seed value is not chan%ed 7or srand788 is not called the !ro%ra -ill use the sa e se*uence o# rando nu "ers each ti e it is run$ 'o chan%e the se*uence o# nu "ers a di##erent seed value ust "e used$ srand78 should only "e called once at the start o# the !ro%ra $

Introduction to C++

Dr Alex Martin 2013

Lecture Set 4 Slide 13

Using Random numbers

+otice that rand78 returns a rando inte%er$ 'y!ically -e -ill "e interested in %eneratin% #loatin% !oint nu "ers #ro so e distri"ution$ 'he si !lest case is the %eneration o# #loatin% !oint nu "ers #ro a 7uni#or 8 distri"ution in so e ran%e Ka4"L $ 'his ay "e %enerated usin% the rand78 #unction usin% an ex!ression li2e& a - (b.a) * (double))and()//012_M03; +otice the ex!licit ty!e conversion achieved "y the 7dou"le8 o!erator$ 7'his is al-ays a %ood idea -hen dividin% t-o inte%ers to ensure that inte%er division is +<' used;8 'he !ro"a"ility distri"ution o# these nu "ers is clearly uni#or over the ran%e Ka4"L$

Introduction to C++

Dr Alex Martin 2013

Lecture Set 4 Slide 14

Using Random numbers


'o %enerate rando such as& inte%er nu "ers in the ran%e a4a+1$$$" an ex!ression

(int)(a - (b.a-+)*(double))and()/(/012_M03-+.&)); should "e used$ +$,$ its necessary to divide "y EA+DIMAJ+1$0 "ecause other-ise one -ill occasionally o"tain "+1$ So4 #or exa !le4 i# one -anted to si ular the toss o# a coin4 -ith tails/heads re!resented "y 0/1$ <ne -ould use& int to = 2*(double))and()/(/012_M03-+.&);

More co !licated distri"utions ay also "e %enerated usin% the "uilt in #unction$ Hor exa !le4 Maussian distri"uted rando nu "ers are used in the exercises$

Introduction to C++

Dr Alex Martin 2013

Lecture Set 4 Slide 1(

A simple Monte Carlo

xample

Hind the area o# a circle 7or the value o# N8 usin% a Monte Carlo

ethod

Idea is to select !oints at rando in the s*uare re%ion -hich encloses the circle o# unit radius and to count the #raction -hich are inside the circle$ <n avera%e the #raction inside the circle should "e %iven "y the ratio o# areas N/4 O 0$6>(

.. . . . . .. .
Dr Alex Martin 2013 Lecture Set 4 Slide 1:

Introduction to C++

A simple Monte Carlo


Hind the area o# a unit circle usin% rando nu "ers

xample

int !"#$$$$% srand(#&'())% int sum"$% for(int i"#% i*!% i++)+ double x " ,# + &-.(double)rand()/RA!01MA2% double y " ,# + &-.(double)rand()/RA!01MA2% if( x.x+y.y * #) sum++% 3 double result " (-. (double)sum/!% cout ** 4 Area of unit circle " 4 ** result ** endl%

Introduction to C++

Dr Alex Martin 2013

Lecture Set 4 Slide 16

5ile I/6
Reading from and 7riting to 5iles using 8treams
'he #strea s !ac2a%e de#ined in F#strea G allo-s one to construct in!ut and out!ut strea s via #iles instead o# via the standard in!ut and out!ut strea s$ 'hese strea s have the #ollo-in% ty!es& Ifstream ofstream input file stream output file stream is created 7 constructed 8 and

'he #ollo-in% code sho-s ho- an in!ut #ile strea destroyed$ i4 t)ea$ input(5input.dat5); ... ... // 2o o$e input 6e)e ... input.clo e();

Introduction to C++

Dr Alex Martin 2013

Lecture Set 4 Slide 1>

5ile I/6
'he state ent i#strea in!ut7)in!ut$dat)81 constructs a in!ut strea in!ut associated -ith the #ile in!ut$dat$ called

'he #unction in!ut$close781 closes the #ile associated -ith the in!ut strea called in!ut a#ter -e have #inished readin% #ro it$

'he construction and destruction o# out!ut #ile strea s is si ilar& o4 t)ea$ output(5output.dat5); ... ... // 2o o$e output 6e)e ... output.clo e();

Introduction to C++

Dr Alex Martin 2013

Lecture Set 4 Slide 1A

5ile I/6

9ere the state ent o#strea out!ut7)out!ut$dat)81 constructs an out!ut strea called out!ut associated -ith the #ile out!ut$dat$ <nce one has constructed an i#strea or o#strea 4 they are use in !retty the sa e -ay as cin or cout$ Hor exa !le& output 77 58ello 9o)ld5 77 endl; <ut!uts the strin% )9ello World) to the #ile out!ut$dat uch

Introduction to C++

Dr Alex Martin 2013

Lecture Set 4 Slide 20

5ile I/6

'he #unctions -ith control #or ated out!ut4 -hich -e discussed !reviously also -or2 on i#strea s$ 'he #ollo-in% code& int x"y":; input ;; x ;; y ;; :; reads an 3 int varia"les #ro the #ile in!ut$dat

More exa !les o# the use o# #strea s can "e #ound in the !ro%ra #strea $c!!

Introduction to C++

Dr Alex Martin 2013

Lecture Set 4 Slide 21

Multi,file programs

?ntil no- all o# the !ro%ra s -e have -ritten have co !rised o# @ust a sin%le $c!! source code #ile$ 'his is <P #or s all !ro%ra s4 "ut #or ore co !lex !ro%ra s 7!ossi"ly -ritten and aintained "y several !ro%ra ers8 it is desira"le to structure the source code into several 7 any8 #iles4 each containin% a collection o# one or ore related #unctions$ ?sually each $c!! -ill have an associated $h header #ile containin% !rototy!es #or all o# the #unctions de#ined in the associated $c!! #ile$ 'his #ile is included into the corres!ondin% $c!! #ile and any other $c!! in -hich its #unctions are used$

Introduction to C++

Dr Alex Martin 2013

Lecture Set 4 Slide 22

Multi,file programs

As an exa !le consider a si !le #unction !rintstr78 Hirst one de#ines a header #ile !rintstr$h 'his contains the lines& <i4nde4 P/I1=>=/_8 <de4ine P/I1=>=/_8 void p)int t)(con t c6a)* <endi4 // P/I1=>=/_8

);

A!art #ro the #unction !rototy!e4 this header #ile contains several !re3!rocessor directives -hich ensure the header #ile is included only once -hen include #iles are nested$

Introduction to C++

Dr Alex Martin 2013

Lecture Set 4 Slide 23

Multi,file programs

'he corres!ondin% $c!! !rintstr$c!! includes the header #ile and the #unction de#inition <include 7io t)ea$; <include 5p)int t).65 void p)int t)(con t c6a)* ) # cout 77 77 endl; %

Introduction to C++

Dr Alex Martin 2013

Lecture Set 4 Slide 24

Multi,file programs

<nce -e have "oth source and header #iles the #unctions they de#ine can "e used #reely in other #unctions$ 'he other #unctions should include the header #ile i$e$ !rintstr$h in this case$ In addition it is necessary to ensure the !rintstr$c!! is co !iled and lin2ed to%ether -ith the ain78 #unction$ So in this instance the #ile4 !rintt$c!!4 containin% the ain78 #unction i%ht loo2 li2e& <include 7io t)ea$; <include 5p)int t).65 int $ain() # p)int t)(58ello 9o)ld5); )etu)n &; %

Introduction to C++

Dr Alex Martin 2013

Lecture Set 4 Slide 2(

Multi,file programs
Hor the Dev C++ co !iler this can "e achieved si !ly "y addin% additional )nodes) to the )tree) enu corres!ondin% to the source code #iles$ ),uild node) on the to!3level $exe node -ill then co !ile all the source #iles and lin2 the to%ether as re*uired$

Introduction to C++

Dr Alex Martin 2013

Lecture Set 4 Slide 2:

T9e :isto ;ac<age

T9e :isto ;ac<age


In order to #acilitate the visualiCation o# data4 a si !le histo%ra in% !ac2a%e is !rovide$ 'his is intended very "asic and is not intended to "e a #ully3#eatured !lottin% !ac2a%e$ Hor no- -e -ill treat it as a 5"lac23"ox5 and si !ly descri"e its use$ 'he header #ile histo$h contains the !ac2a%e declarations and the i !le entation are contained in histo$c!!$ An exa !le o# the use o# this !ac2a%e is !rovided in the exa !le hexa !le$c!!$ 'his !ro%ra si ulates the thro- o# a !air o# dice and histo%ra s the su o# the t-o scores$

Introduction to C++

Dr Alex Martin 2013

Lecture Set 4 Slide 26

T9e :isto ;ac<age


In the hexa !le$c!! exa !le !ro%ra the line&

8i to $y6i to( 2.&" +3.&" ++ );

Declares a histo%ra called yhisto -hich has 11 "ins$ 'he #irst "in starts at 2$0 and the last "in ends at 13$0$ Qntries are added to the histo%ra "y the state ent&

$y6i to.accu$ulate( d+ - d2 );

Hinally the histo%ra

can "e !lotted&

$y6i to.plot();

Introduction to C++

Dr Alex Martin 2013

Lecture Set 4 Slide 2>

T9e :isto ;ac<age

'y!ical out!ut #ro

this exa !le is&

Introduction to C++

Dr Alex Martin 2013

Lecture Set 4 Slide 2A

Using Random numbers

Introduction to C++

Dr Alex Martin 2013

Lecture Set 4 Slide 30

Introduction to C++

Introduction to C++

Dr Alex Martin 2013

Lecture Set 4 Slide 31

Вам также может понравиться