Tải bản đầy đủ (.ppt) (28 trang)

C++ lecture 10

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (163.55 KB, 28 trang )

C++ Programming
Lecture 10

Functions – Part II

The Hashemite University
Computer Engineering Department
Adapted from the textbook slides.


Outline







Introduction.
Random numbers generation in C+
+.
enum data type identification and
usage.
Examples.

The Hashemite University

2


Random Number


Generation I








Random number generation is used mainly
in simulation and game playing based
application.
The rand() function is used in C++ to
generate random integer numbers between
0 and a maximum specified value.
rand() function takes nothing (i.e. void) as its
arguments and returns an unsigned integer.
In order to use this function you must Load

<cstdlib> or <stdlib.h>
The Hashemite University

3


Random Number
Generation II


rand


function syntax:
int i = rand();



Generates a pseudorandom number between 0 and
RAND_MAX (usually 32767)










RAND_MAX is a symbolic constant defined in the stdlib
header file.
0 <= rand() <= RAND_MAX.
A pseudorandom number is a preset sequence of
"random" numbers.
The same sequence is generated upon every program
execution, is this preferred?.
This repeated behavior is essentially in programming
debug and verification in simulation and other randombased applications.
The Hashemite University
4



Random Numbers Seeding I


srand function











Jumps to a seeded location in a "random" sequence.
Similar to rand() function, srand function is defined in
the <stdlib.h> library.
Takes an unsigned integer as a seed (i.e. as an
argument).
It does not return any value (returns void), it just
change the random sequence (randomizing the rand()
function).
Can be called more than once within the same
program.
Still you need to use the rand() function to get the
random numbers.
The Hashemite University


5


Random Numbers Seeding
II


srand

syntax:

srand( seed );

seed can be any unsigned integer
entered manually be the user or
initialized through the program.
 If the same seed is used every
time the program is run we will
get the same random sequence
(i.e. the same without seed).


The Hashemite University

6


Rand example
#include <iostream>
#include<cstdlib>

using namespace std;
int main ()
{
for(int i=0;i<10;i++)
{
cout<}
return 0;
}

The Hashemite University

7


Rand example (2)
#include <iostream>
#include<cstdlib>
using namespace std;
int main ()
{
for(int i=0;i<7;i++)
{
cout<l;
}
return 0;
}

The sequence is repeated every

time
The Hashemite University

8


Now use srand()
#include <iostream>
#include<cstdlib>
using namespace std;
int main ()
{
srand(3);
for (int i=0;i<5;i++)
{
cout<}
return 0;
}

The random sequence is changed , however if you run this code more than
one time, the same set of random numbers will be displayed every time
The Hashemite University

9


So that…
41
18467

6334
26500
19169
15724
..
The sequence before calling
srand()

48
7196
9294
9091
7031
..

The sequence after calling
srand()

Thus, calling srand() will change the sequence of random numbers
given that you change the seed value passed ti it, otherwise if the
same seed value the same random numbers will appear over and over
again.
The Hashemite University
10


Random Numbers Seeding
III



To initialize seed value automatically use
the following syntax:
srand( time( 0 ) );







time( 0 )

Returns the current calendar time in seconds.

time() function takes a pointer as an argument and
returns unsigned integer.
Changes the seed every time the program is run,
thereby allowing rand() to generate random numbers.
So, it is much better than manual seeding.
Need to include the <ctime> or <time.h> library to use
the time() function.
The Hashemite University

11


Changing Random
Numbers Range I



Scaling and shifting
 Reduces random number to a certain range
 Modulus ( % ) operator


Reduces number between 0 and RAND_MAX to a
number between 0 and the scaling factor:
Number = offset (shift value) + rand() % scaling_factor



Example


i = rand() % 6 + 1;
Generates a number between 1 and 6
The Hashemite University

12


Changing Random Numbers
Range II


Scaling and shifting equations:


Lets assume the range is [min, max], then:
Offset = min.

Scaling factor = max – min + 1



Lets assume the range is [min, max)  [min,
max-1], then:
Offset = min.
Scaling factor = max – min



Lets assume the range is (min, max][min+1,
max], then:
Offset = min + 1.
Scaling factor = max – min



Continue for other possibilities .....
The Hashemite University

13


Random numbers example
Write a c++ code (using functions) to generate 10 random
numbers in the range of (7,25) (i.e. generated x must satisfy 7
< x<iostream>
< 25).
#include



#include<cstdlib>
using namespace std;
int random();
int main ()
{
for(int i=0;i<10;i++)
{
cout<}
return 0;
}
int random()
{

return 8+rand()%17;
}

Note: even if you don’t use functions, the same
output will be displayed for you
The Hashemite University

14


Changing Random Numbers
Range III



All the previous equations are used to generate
integers but what about floating point random
numbers?








First: convert the floating point range into an integer
range by multiplying the range by 10^n where n is at
least the number of digits after the decimal point.
Second: find the values of both the offset and scaling
factor based on the equations in the previous slide.
Third: divide the resulting random number on 10^n to
get a floating point random number in the specified
range.
Note that n controls the difference value (lets call it the
step width) between the generated random numbers.
The Hashemite University

15


Examples


Generate random numbers in the following

ranges:






100 <= n <= 200  int n = 100 + rand()%101
100 <= n < 500  int n = 100 + rand()%400
50 < n <= 200  int n = 51 + rand()%150
100 < n < 200  int n = 101 + rand()%99
0.01 <= n <= 0.08 
double n = (1 + rand()%8)/100 -- with step width = 0.01
Or double n = (10+rand()%71)/1000



0.02 <= n <= 0.9 
double n = (20 + rand()%881)/1000 -- with step width = 0.001
The Hashemite University

16


1
2
3
4
5
6

7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

// Fig. 3.7: fig03_07.cpp
// Shifted, scaled integers produced by 1 + rand() % 6
#include <iostream>
using std::cout;
using std::endl;
#include <iomanip>
using std::setw;
#include <cstdlib>
int main()
{
for ( int i = 1; i <= 20; i++ ) {

cout << setw( 10 ) << ( 1 + rand() % 6 );

Notice rand() % 6 . This returns a number
between 0 and 5 (scaling). Add 1 to get a
number between 1 and 6.

if ( i % 5 == 0 )
cout << endl;
}

Executing the program again gives the
same "random" dice rolls.

return 0;
}

5
2
5
5

5
4
3
1

3
2
2
4


5
5
2
6

5
5
1
4

The Hashemite University

17


1
2
3
4
5
6
7
8
9
10
11
12
13
14

15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

// Fig. 3.9: fig03_09.cpp
// Randomizing die-rolling program
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include <iomanip>
using std::setw;
#include <cstdlib>
int main()
{
unsigned seed;

cout << "Enter seed: ";
cin >> seed;
srand( seed );
for ( int i = 1; i <= 10; i++ ) {
cout << setw( 10 ) << 1 + rand() % 6;
if ( i % 5 == 0 )
cout << endl;
}
return 0;
}

The Hashemite University

18


Enter seed: 67
1
5

6
6

5
3

1
1

4

2

Enter seed: 432
4
2

2
5

6
1

4
4

3
4

Enter seed: 67
1
5

6
6

5
3

1
1


4
2

Notice how the die rolls
change with the seed.

Program Output

The Hashemite University

19


Enumeration I






It is the counterpart of symbolic constants found in
C (to assign integer values to symbolic constants).
The main difference is that enum can define a new
data type within the program.
Enumeration - set of integers with identifiers
enum typeName {constant1, constant2…};




Constants start at 0 (default), incremented by 1
Unique constant names

The Hashemite University

20


Enumeration II




If you don't specify values for enum constants, the values start
at zero and increase by one with each move down the list.
E.g:
enum MyEnumType { ALPHA, BETA, GAMMA }; ALPHA has a value
of 0, BETA has a value of 1, and GAMMA has a value of 2.



If you want, you may provide explicit values for enum
constants, as in
enum Size { SMALL = 10, MEDIUM = 100, LARGE = 1000 };



Or
enum Size { SMALL = 10, MEDIUM, LARGE }; //here MEDIUM will have
the value of 11 and LARGE will have the value of 12






You can assign positive and negative integer values to enum
constants (but not floating point values which will be a syntax
error).
enum Size { SMALL = -10, MEDIUM, LARGE }; //here MEDIUM
will have the value of -9 and LARGE will have the value of -8
The Hashemite University

21


Enumeration III


There are two kinds of enum type declarations.


One kind creates a named type, as in
enum MyEnumType { ALPHA, BETA, GAMMA };
If you give an enum type a name, you can use that type for
variables, function arguments and return values, and so on:
E.g:
MyEnumType y;




The other kind creates an unnamed type. This is
used when you want names for constants but don't
plan to use the type to declare variables, function
arguments, etc.
For example, you can write enum { HOMER, MARGE, BART,
LISA, MAGGIE };
The Hashemite University

22


C++ enum type
conversion rules




There is an implicit conversion from any enum
type to int.
E.g:
enum MyEnumType { ALPHA, BETA, GAMMA };
Then the following lines are legal:
int i = BETA; // give i a value of 1
int j = 3 + GAMMA; // give j a value of 5



On the other hand, there is not an implicit
conversion from int to an enum type:
MyEnumType x = 2; // syntax error

MyEnumType y = 123; // syntax error
The Hashemite University

23


Enumeration Example I
#include<iostream.h>
int main()
{
enum cars{BMW, MAZDA, KIA, BENZ};
cars mycar;
int money, i,
BMW_price = 1000,
MAZDA_price = 100,
KIA_price = 500,
BENZ_price = 2000;
cout << "Enter the car type (BMW = 0, MAZDA = 1, KIA = 2, BENZ =
3):\n";
cin >> i;
mycar = (cars)i;
cout << "Enter the money balance:\n";
cin >> money;
The Hashemite University

24


Enumeration Example II
switch(mycar)

{
case BMW:
if(money >= BMW_price)
cout << "You can buy car " << mycar << endl;
else
cout << "You cannot buy car " << mycar << endl;
break;
case MAZDA:
if(money >= MAZDA_price)
cout << "You can buy car " << mycar << endl;
else
cout << "You cannot buy car " << mycar << endl;
break;

The Hashemite University

25


Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×