课件chp2数据类型与表达式_第1页
课件chp2数据类型与表达式_第2页
课件chp2数据类型与表达式_第3页
课件chp2数据类型与表达式_第4页
课件chp2数据类型与表达式_第5页
已阅读5页,还剩73页未读 继续免费阅读

付费下载

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

12021/7/17

1C/C++程序设计主讲

中南大学软件学院谭长庚Chapter

22021/7/172ObjectivesTo

write

C++

programs

(§2.2-2.5)1Data

type

and

convert

ing2Variable

and

constant3Operator

,expression

and

assignment

statement45

To

have

a

unified

styleTo

distinguish

syntax,

runtime,

logic

errors-debug2021/7/17362.1数据类型2021/7/174数据类型的概念数据是程序的一个重要组成部分,数据的描述用数据类型来给出,每个数据都属于某种数据类型。一种数据类型可以看成由两个集合构成:值集:描述该数据类型包含哪些值操作(运算)集:描述了对值集中的值能实施哪些运算。例如:整数类型就是一种数据类型,它的值集就是由整数所构成的集合,它的操作集包括:加、减、乘、除等运算。数据类型一般可以分为:简单数据类型:值集中的数据是不可再分解的简单数据,如:整数类型、实数类型等;复合数据类型:值集中的数据是由其它类型的数据按照一定的方式组织而成,如:向量、矩阵等。区分数据类型的好处对数据进行分类,便于数据的处理。提高程序的可靠性,便于编译程序自动进行类型一致性检查。便于产生高效代码2021/7/1752.C++数据类型2021/7/176C++把数据类型分为:基本数据类型C++语言预先定义好的数据类型,常常又称为标准数据类型或内置数据类型(built-intypes),它们都是简单类型。构造数据类型用户利用语言提供的类型构造机制从其它类型构造出来的数据类型,它们大多为复合数据类型(枚举类型除外)。抽象数据类型用户利用数据抽象机制把数据与相应的操作作为一个整体来描述的数据类型。它们一般为复合数据类型。2021/7/17

7派生类类抽象数据类型引用类型指针类型数组类型枚举类型空值类型实数类型构造数据类型结构与联合类型C

++数据类型整数类型intfloat,double基本数据类型字符类c型har逻辑类型boolvoid3.C++基本数据类型2021/7/178C++基本数据类型指的是语言预定义的数据类型,称为标准或内置数据类型C++基本数据类型对应着能由计算机直接表示和处理(机器指令能对它们直接进行操作)的数据类型,包括:整数类型实数类型字符类型逻辑类型空值类型表2-1

常用基本数据类型描述2021/7/17类型说明长度表示范围备注bool逻辑型1false,truecharwchar_t字符型1-128~127-27~(27-1)unsigned

char无符号字符型10~2550~(28-1)short短整形2-32768~32767-215~(215-1)unsigned

short无符号短整型20~655350~(216-1)int整型4-2147483648

~2147483647-231~(231-1)unsignedint无符号整型40~0~(232-1)long长整型4-2147483648

~2147483647-231~(231-1)unsigned

long无符号长整型40~0~(232-1)float浮点型4-3.4×1038~3.4×10387位有效位double双精度8-1.7×10308~1.7×1030817位有效位long

double长双精度8(12)-1.18E

to3.39

7E-493219位有效位Synonymous

Types-同义类型2021/7/1710short

int =>

short.

unsigned

short

int

=>

unsigned

short.unsigned

int =>

unsigned.long

int =>

long.

unsigned

long

int =>

unsigned

long.For

example,short

int

i

=

2;is

same

asshort

i

=

2;sizeof

operator2021/7/1711Use

the

sizeof

tofind

the

size

of

a

type(确定类型或变量占用内存字节数).The

followingstatement

displays

the

sizeofint,x,

and

double

on

your

machine.floatx;cout

<<

sizeof(int)

<<

"

"

<<

sizeof(x)

<<

"

"

<<

sizeof(double);The

output

?4484.Numeric

Literals-数值文字常量2021/7/1712A

literal

is

a

constant

value

that

appearsdirectlyin

aprogram.For

example,

34,

1000000,

and

5.0

areliterals

in

the

following

statements:int i

=

34;long k

=

1000000;double d

=

5.0;整数类型字面常量2021/7/1713整数类型字面常量的类型为int。可在整数类型常量的后面:加上l或L,表示long

int类型的常量,如:32765L也可加上u或U,表示unsignedint类型的常量,如:4352U也可同时加上u(U)和l(L)表示unsigned

long类型的常量,如:41152UL或41152LU使用10、8、16进制表示整数。octal

and

hex

literals-八进制与十六进制By

default,

an

integer

literal

is

a

decimal

number.默认整型字面常量为10进制To

denote

an

octal

integer

literal,

use

a

leading

0To

denote

a

hexadecimal

integer

literal,

use

a

leading

0x

or0X

(zero

x).For

example,

the

following

code

displays

the

decimal

value65535

for

hexadecimal

number

FFFF

and

decimal

value

8

foroctal

number

10.cout<<0xFFFF

<<“”<<010;//输出结果为10进制注意:八进制与十六进制只用来表示整数。2021/7/1714实数类型字面常量2021/7/1715实数类型字面常量为double型。可以在实数类型常量后面加上F(f)以表示float型,如:5.6F。也可加上L(l)表示long

double型,如5.6L。十进制小数形式:由数字和小数点组成;例如:3.4,4.,.3。指数形式:“十进制小数”+“

e(或E)”+“十进制数整数”。例如:

12.5e-6

表示12.5×10-6

。§

小数点不能单独出现;

0.√

.0

.

·§e或E的两边必须有数,且其后面必须为整数;如:

6E0.2·

e5

·why

called

floating-point?2021/7/1716The

float

and

double

types

are

used

to

representnumbers

with

a

decimal

point.

Why

are

they

calledfloating-point

numbers?

These

numbers

are

storedinto

scientific

notation.

When

a

number

such

as50.534

is

converted

into

scientific

notation

such

as5.0534e+1

,its

decimal

point

is

moved

(i.e.,

floated)to

a

new

position.3123.35=>31.2335×102=>3.12335×103120

、-100、0;0120、072;0xFFFF、0x1e、0X28AF,0XED4

;120L,

200L

长整型常量3.14、-3.1、5.12E-6

;'a'、'#'、'\n'、'\101'

;099、12f、0xg

、48EA

;019.5

、1e-08;实型常量只能用十进制形式表示2.1E10.2、E-6、6.4E+4.8、E9

;"changsha"

、"+++\\?ab";'\'、'\p'

、'''、'ab'

;请判断这些常量正确与否:错2021/7/17172.2

Variables

and

constants2021/7/1718变量:其值在程序中可以改变的量常量:其值在程序中不能改变的量,如10//

Compute

the

first

area

radius

=

1.0;area

=

radius

*

radius

*

3.14159;std::cout

<<

area;//

Compute

the

second

area

radius

=

2.0;area

=

radius

*

radius

*

3.14159;std::cout

<<

area;Declaring

Variables-声明变量2021/7/1719声明变量:给变量命名,确定类型intx;////Declareintegerx

to

be

anvariable;doubleradius;////Declare

radius

tobe

a

double

variable;char

a;//

Declare

a

to

be

a//

character

variable;1、定义形式:类型标识符:变量名1[,变量名2,变量名3...];例如:inta,b,c

;float

x,y;自己设定,满足标识符的规定。如:int,float,char;不可省char

c1,c2;或int

c1,c2;2、变量初始化在说明变量的同时给变量一个初始值。例如int

a=5,

b=3;

√int

a=b=c=3;

·int

a,b,c;

a=b=c=3;√2021/7/17202.3

Named

Constants-命名常量2021/7/1721const

datatype

CONSTANTNAME

=

VALUE;const

double

PI

=

3.14159;const

int

SIZE

=

3;PI与SIZE的值都不能改变:

PI=3.14;×2.4

Assignment

Statements-赋值语句1.赋值语句2021/7/1722int

x;double

radius;char

a;x

=

1;//

Assign

1

to

x;radius

=

1.0;

//

Assign

1.0

to

radius;a

=

‘A’;x=10;//

Assign

‘A’

to

a;//x的值为10Declaring

and

Initializing

in

One

Step声明变量时进行初始化int

x

=

1;double

d

=

1.4;3.Shorthand

Assignment

Operators(简写赋值运算符)2021/7/1723OperatorExampleEquivalent+=i+=8i=i+8-=f-=8.0f=f-8.0*=i*=8i=i*8/=i/=8i=i/8%=i%=8i=i%84.Increment

and

Decrement

Operators2021/7/1724(增1与减1运算符)Operator++varvar++--varvar--Namepreincrement(先增)postincrement(后增)predecrement(先减)postdecrement(后减)DescriptionThe

expression

(++var)

increments

varby

1

and

evaluatesto

the

new

value

in

var

after

the

increment.The

expression

(var++)

evaluates

to

the

original

valuein

var

and

increments

var

by

1.The

expression

(--var)

decrements

var

by

1

and

evaluatesto

the

new

value

in

var

after

the

decrement.The

expression

(var--)

evaluates

to

the

original

valuein

var

and

decrements

var

by

1.自增与自减运算符等价于i=i+1;j=i;i++;所以i的值为4,j的值为3。i++;j=i;所以i的值为4,j的值为4。“++i,--i:使用之前使i的值增1(或减1);“i++,i--:使用之后使i的值增1(或减1);例如:2021/7/1725(1)

i++;++i;(2)

i=3;j=i++;(3)

i=3;j=++i;Increment

andDecrement

Operators,

cont.int

i

=

10;int

newNum

=

10

*

i++;int

newNum

=

10

*

ii

=

i

+

1;Same

effect

asint

i

=

10;int

newNum

=

10

*

(++i);i

=

i

+

1;int

newNum

=

10

*

iSame

effect

as2021/7/1726Increment

andDecrement

Operators,

cont.2021/7/1727Using

increment

anddecrement

operatorsmakesexpressions

short,

but

it

also

makes

them

complex

anddifficult

to

read.

Avoid

using

these

operators

in

expressionsthat

modify

multiple

variables,

or

the

same

variable

formultiple

times

such

as

this:

int

k

=

++i

+

i.注意:应该避免编写结果依赖于运算对象求值顺序的代码5.Assignment

Expressions

,

Statements(赋值表达式与赋值语句)Prior

to

Java

2,

all

the

expressions

can

be

usedas

statements.

Since

Java

2,

only

the

followingtypes

of

expressions

can

be

statements:variable

op=

expression;

//

Where

op

is

+,

-,

*,/,

or

%++variable;variable++;--variable;variable--;Int

x,y=3;X=5+y;Cout<<x=5+y;2021/7/1728赋值语句

赋值表达式#include

<iostream>using

namespace

std;void

main(void){const

int

PRICE=30;intnum,total;float

v

,r,h;num=10;total=num*PRICE;cout<<total

<<endl;r=2.5;h=3.2;v=3.14159*r*r*h;cout<<v<<endl;}常量变量变量先声明后使用符号常量2021/7/1729Page

292.5 Introducing

Programmingwith

an

Example(变量与常量的使用)#include

<iostream>using

namespace

std;void

main(void){const

int

PRICE=30;intnum,total;float

v,r,h;num=10;total=num*PRICE;cout<<total

<<endl;r=2.5;h=3.2;v=3.14159*r*r*h;cout<<v<<endl;}short

unsigned

short2字节

int、unsigned

int4字节long

unsigned

long4字节整型变量整型变量声明整型常量2021/7/1730Listing

2.1

Computing

the

Area

ofa

Circle2021/7/1731This

program

computes

theareaof

thecircle.Trace

a

Program

Execution#include

<iostream>int

main()

{double

radius;double

area;//

Step1:Read

inradiusradius

=20;//

Step

2:Computeareaarea

=radius

*

radius

*

3.14159;//

Step

3:

Display

the

areastd::cout

<<"The

area

is

";std::cout

<<

area<<

std::endl;}no

valueradiusallocate

memoryfor

radius2021/7/1732Trace

a

Program

Executionno

valuememorydouble

area;#include

<iostream>int

main()

{double

radius;//

Step1:Read

inradiusradius

=20;//

Step

2:Computeareaarea

=radius

*

radius

*

3.14159;//

Step

3:

Display

the

areastd::cout

<<"The

area

is

";std::cout

<<

area<<

std::endl;}no

valueradiusareaallocate

memoryfor

area2021/7/1733Trace

a

Program

Execution20no

valueradiusareaassign

20

to

radius#include

<iostream>int

main()

{double

radius;double

area;//

Step1:Read

inradiusradius

=20;//

Step

2:Computeareaarea

=radius

*

radius

*

3.14159;//

Step

3:

Display

the

areastd::cout

<<"The

area

is

";std::cout

<<

area<<

std::endl;}2021/7/1734Trace

a

Program

Execution20memory1256.636radiusareacompute

area

and

assign

itto

variable

area#include

<iostream>int

main()

{double

radius;double

area;//

Step1:Read

inradiusradius

=20;//

Step

2:Computeareaarea

=radius

*

radius

*

3.14159;//

Step

3:

Display

the

areastd::cout

<<"The

area

is

";std::cout

<<

area<<

std::endl;}2021/7/1735Trace

a

Program

Execution20memory1256.636radiusareaprint

a

message

to

theconsole#include

<iostream>int

main()

{double

radius;double

area;radius

=

20;

//

Step

1:

Read

inradiusarea

=radius

*

radius

*

3.14159;//

Step

2:Compute

areastd::cout

<<"The

area

is

";std::cout

<<

area<<

std::endl;//

Step

3:

Display

the

area}2021/7/17362.6

Reading

Input

from

the

Keyboard2021/7/1737You

can

use

the

std::cin

object

to

readinput

from

the

keyboard.#include

<iostream>int

main(){ //

Step

1:

Read

in

radiusdouble

radius;std::cout

<<

"Enter

a

radius:

";std::cin

>>

radius;//

Step

2:

Compute

areadouble

area

=

radius

*

radius

*

3.14159;//

Step

3:

Display

the

areastd::cout

<<

"The

area

is

"

<<

area

<<

std::endl;}2.7

Omitting

the

std::

Prefix2021/7/1738Notice:

std::cout,

std::endl,

and

std::cin

allstart

with

std::.std

means

the

standard

namespace.C++

divides

the

world

into

“namespaces”

toresolve

potential

naming

conflicts.std::cout

means

that

cout

belongs

to

thestandard

namespace

std.Add

the

statement:using

namespace

std;to

eliminate

the

std::

prefix.Add

the

statement:

using

namespace

std;#include

<iostream>using

namespace

std;

int

main(){ //

Step

1:

Read

in

radiusdouble

radius;cout

<<

"Enter

a

radius:

";cin

>>

radius;//

Step

2:

Compute

areadouble

area

=

radius

*

radius

*

3.14159;//

Step

3:

Display

the

areacout

<<

"The

area

is

"

<<

area

<<

endl;}nostd::2021/7/17392.8

Identifiers2021/7/1740An

identifier

is

a

sequence

of

characters

thatconsists

of

letters,

digits,

and

underscores(_).An

identifier

must

start

with

a

letter

or

anunderscore.

It

cannot

start

with

a

digit.An

identifier

cannot

be

a

reserved

word.(See

Appendix

A,

“C++

Keywords,”

for

a

listof

reserved

words.)An

identifier

can

be

of

any

length,

but

yourC++

compiler

may

impose

some

restriction.Use

identifiers

of

31

characters

or

fewer

toensure

portability.2.

9

Operators

and

expressionName

Meaning

Example

Result+Addition34+135-Subtraction34.0

0.133.9*Multiplication300

*

309000/Division1.0

/

2.00.5%Remainder20

%32模运算/求余,两操作数必须为整数1.数值运算符2021/7/1741IntegerDivision

+,-,*,

/,

and

%5/2

yields

an

integer

2.(小数被截除)5.0/

2

yields

a

double

value2.5

5

%

2

yields

1

(the

remainder

of

thedivision)-5%2

yields

-1

;余数的符号同被除数%运算符要求两个操作数都为整数:3.2%2

×2021/7/1742Remainder

OperatorA

week

has

7

daysAfter

10

daysThe

2nd

day

in

a

week

is

Tuesday(6

+

10)

%

7

is

2

For

example,

an

even

number

%

2

is

always

0

and

anodd

number

%

2

is

always

1.Soyou

can

use

thisproperty

to

determine

whether

anumber

is

even

or

odd.Suppose

today

isSaturday

andyouandyour

friendsare

going

to

meet

in

10

days.

What

day

is

in

10

days?You

can

find

that

day

is

Tuesday

using

the

following

expression:Saturday

is

the

6th

day

in

a

week2021/7/1743算术运算符和算术表达式1、运算符+(加):3+4、+3-(减):3-5、-5*(乘):3*5/(除):5/2的值为2;5.0/2的值为2.5;%(取余):5%3的值为2;-5%3的值为-2;5%(-3)的值为2;-5%(-3)的值为-2;12.3%3

×若a能被b整除,则有:a%b==02021/7/1744Example:

Displaying

Time2021/7/1745Write

a

program

that

obtains

hours

andminutes

from

500

seconds.#include

<iostream>using

namespace

std;int

main(){

int

seconds

=500;int

minutes

=

seconds

/

60;int

remainingSeconds

=

seconds

%

60;cout

<<seconds

<<"

seconds

is

"

<<

minutes<<"

minutes

and

"

<<

remainingSeconds<<"

seconds

"

<<

endl;return

0;}Overflow(溢出)2021/7/1746When

a

variable

is

assigned

a

value

that

istoo

large

to

be

stored,

it

causes

overflow.For

example,

executing

the

followingstatement

causes

overflow.short

value

=

32767

+

1;Why?The

largest

value

that

canbe

stored

in

a

variableof

the

short

type

is

32767.

32768

is

too

large.Underflow(下溢)2021/7/1747When

avariable

isassigned

avaluethat

is

too

small

to

be

stored,

itcauses

underflow.For

example,

executing

the

followingstatement

causes

underflow,the

smallest

value

that

can

be

storedin

a

variableof

the

short

type

is-32768.

-32769

is

too

small.short

value

=-32769;2.Arithmetic

Expressions(算术表达式)由数值、小括号、算术运算符按一定规则构成的式子,如:3

+

4x

-

10(

y

-

5)(a

+

b

+

c)

+

9(

4

+

9

+

x

)5

x

x

yis

translated

to注意写法、计算顺序、括号嵌套(3+4*x)/5

10*(y-5)*(a+b+c)/x

+

9*(4/x

+

(9+x)

/y)2021/7/1748Example:ConvertingTemperaturesWrite

a

program

that

converts

aFahrenheit

degree

to

Celsius

using

theformula:9celsius

=

(

5

)(

fahrenheit

-

32)#include

<iostream>using

namespace

std;int

main(){

//

Enter

a

degree

in

Fahrenheit

double

fahrenheit;cout

<<

"Enter

a

degree

in

Fahrenheit:

";cin

>>

fahrenheit;

//

Obtain

a

celsius

degreedouble

celsius

=

(5.0

/

9)

*

(fahrenheit

-

32);//

Display

resultcout

<<

"Fahrenheit

"

<<

fahrenheit

<<

"

is

"<<

celsius

<<

"

in

Celsius"

<<

endl;return

0;}2021/7/17492.10

Numeric

Type

Conversion2021/7/1750(数值类型转换)Consider

the

following

statements:short

i

=

100;long

k

=

i

*

3

+

4;double

d

=

i

*

3.1

+

k

/

2;1.Conversion

Rules(转换规则)2021/7/1751When

performing

a

binary

operation

involvingtwo

operandsof

different

types,

Javaautomatically

converts

the

operandbased

on

the

following

rules:If

one

of

the

operands

is

long

double,

the

other

isconverted

into

long

double.Otherwise,

if

one

of

the

operands

is

double,

theother

is

converted

into

double.Otherwise,

if

one

of

the

operands

is

float,

the

otheris

converted

into

float.Otherwise,

if

one

of

the

operands

is

unsigned

long,the

other

is

converted

into

unsigned

long.Otherwise,

if

one

of

the

operands

is

long,

the

otheris

converted

into

long.Otherwise,

if

one

of

the

operands

is

unsigned

int,the

other

is

converted

into

unsigned

int.Otherwise,

both

operands

are

converted

into

int.floatdoublelongunsignedintchar,shortC++语言允许整型、实型、字符型数据进行混合运算。有3种转换方式:自动转换、赋值转换和强制转换。一、类型自动转换(Implicit

casting-隐含转换)double

d

=

3;

(type

widening)2021/7/17522.Type

Casting二、Explicit

casting(显式转换/手动转换)格式:static_cast<新类型>(被转换数据);int

i

=

static_cast<int>(3.0);//(type

narrowing)int

i

=

(int)3.9;//(Fraction

part

is

truncated)i=32021/7/1753NOTE2021/7/1754Casting

does

not

change

the

variable

being

cast.

For

example,

d

is

not

changed

after

casting

inthe

following

code:double

d

=

4.5;int

i

=

static_cast<int>(d); //

d

is

not

changed

cout<<i<<d;输出结果?输出结果:4

4.5

D本身的值没变。2.11字符数据类型(Character

Data

Type)char

letter

=

'A';

(ASCII)char

numChar

=

'4';

(ASCII)NOTE:++、--运算符可以用于char类型变量,得到后与前一字符.char

ch

=

'a';

cout

<<

++ch;显示字符bHow

to

read

a

character

from

the

keyboard?cout

<<

"Enter

a

character:

";char

ch;cin

>>

ch;2021/7/1755Escape

Sequences

for

SpecialCharacters转义序列表示特殊符号:反斜杠开始后跟一符号CharacterEscapeSequenceNameASCIICode\bBackspace8\tTab9\nLinefeed10\fFormfeed12\rCarriageReturn13\\Backslash92\'Single

Quote39\"Double

Quote342021/7/17561.字符类型字面常量2021/7/1757在C++程序中,字符常量是由两个单引号(')括起来的一个字符构成,其中的字符写法可以是:字符本身,如:'A'转义序列,由\打头的一串符号字符的编码八进制:'\ddd',如:'\101'十六进制:'\xhh',如:'\x41'特殊表示,如:'\n'(换行符)、'\r'(回车符)、'\t'(横向制表符)、'\b'(退格符)等注意下列字符的表示:反斜杠(\)应写成:'\\'单引号(')应写成:'\''双引号(“)可写成:‘\”’2021/7/17582.字符串类型字面常量2021/7/1759在C++程序中,字符串常量是由两个双引号(")括起来的字符序列构成,其中的字符的写法与字符类型常量基本相同,即可以是字符本身和转义序列。如:"This

is

a

string.""I'm

a

student.""Please

enter

\"Y\"

or

\"N\":""This

is

two-line

\nmessage!

"存储字符串时,往往要在最后一个字符的后面存储一个字符’\0’,表示字符串结束。字符常量与字符串常量的区别字符常量表示单个字符,其类型为字符类型(char);而字符串常量可以表示多个字符,其类型为一维的常量字符数组(构造数据类型)。字符常量用单引号表示;而字符串常量用双引号表示。对字符常量的操作按char类型进行;对字符串常量的操作按字符数组的规定。字符常量在内存中占一个字节;字符串常量占多个字节,其字节数为:字符串中的字符个数加上1。'A'2021/7/1760"A"AA\0Appendix

B:

ASCII

Character

SetASCII

Character

Set

is

a

subset

of

the

Unicode

from

\u0000

to

\u007f2021/7/1761ASCII

Character

Set,

cont.ASCII

Character

Set

is

a

subset

of

the

Unicode

from

\u0000

to

\u007f2021/7/17623.Casting

between

char

and

Numeric

Types2021/7/1763字符型与整型间的转换int

i

=

'a';

//

Same

as

int

i

=

(int)'a';char

c

=

97;

//

Same

as

char

c

=

(char)97;4.Numeric

Operators

on

Characters2021/7/1764The

char

type

is

treated

as

if

it

is

an

integer

of

the

byte

size. All

numeric

operators

can

be

applied

to

char

operands.

A

char

operand

is

automatically

cast

into

a

number

if

theother

operand

is

a

number

or

a

character.以其ASC码值参与运算

int

i

=

'2'

+

'3';

//

(int)'2'

is

50

and

(int)'3'

is

51cout

<<

"i

is

"

<<

i

<<

endl;

//

i

is

decimal

101int

j

=

2

+

'a';

//

(int)'a'

is97cout

<<

"j

is

"

<<

j <<

endl;cout

<<

j

<<

"

is

the

ASCII

code

for

character

"

<<static_cast<char>(j)

<<

endl;Display:i

is

101j

is

9999

istheASCII

code

forcharactercNote2021/7/1765It

is

worthwhile

to

note

that

the

ASCII

for

lowercaseletters

are

consecutive

integers

starting

from

thecode

for

'a',

then

for

'b',

'c',

...,

and

'z'.

The

same

istrue

for

the

uppercase

letters.Furthermore,

the

ASCII

code

for

'a'

is

greater

thanthe

code

for

'A'.

So

'a'

-

'A'

is

the

same

as

'b'

-

'B'.For

a

lowercase

letter

ch,

its

corresponding

uppercase

letter

is

static_cast<char>('A'

+

(ch

-

'a')).floatdoublelongunsignedintchar,short12.0/3float

a=2.0;

int

b

=6,c

=3;a*b/c

-1.5

+’a’

+fabs(-5)54.0

-

1.52.5

+97(int)99.5

+

5104.5(double)例:计算表达式的值2021/7/1766Example:12021/7/17671-(1+

monthlyInterestRate)numberOfYears·12Computing

LoanPaymentsThis

program

letsthe

user

entertheinterestrate,

number

of

years,

and

loan

amount

andcomputesmonthly

paymentand

totalpayment.loanAmount

·

monthlyInterestRate2021/7/17

68#include

<iostream>#include

<cmath>using

namespace

std;int

main()

{

//

Enter

yearly

interest

ratecout

<<

"Enter

yearly

interest

rate,

for

example

8.25:

";double

annualInterestRate;cin

>>

annualInterestRate;

//

Obtain

monthly

interest

ratedouble

monthlyInterestRate

=

annualInterestRate

/

1200;

//

Enternumber

of

yearscout

<<

"Enter

number

of

years

as

an

integer,

for

example

5:

";int

numberOfYears;

cin

>>

numberOfYears;

//

Enter

loan

amountcout

<<

"Enter

loan

amount,

for

example

120000.95:

";double

loanAmount;

cin

>>

loanAmount;

//

Calculate

paymentdouble

monthlyPayment

=

loanAmount

*

monthlyInterestRate

/

(1

-

1

/pow(1

+

monthlyInterestRate,

numberOfYears

*

12));double

totalPayment

=

monthlyPayment

*

numberOfYears

*

12;//

Format

to

keep

two

digits

after

the

decimal

pointmonthlyPayment

=

static_cast<int>(monthlyPayment

*

100)

/

100.0;totalPayment

=

static_cast<int>(totalPayment

*

100)

/

100.0;

//

Displayresultscout

<<

"The

monthly

payment

is

"

<<

monthlyPayment

<<

"\nThe

totalpayment

is

"

<<

totalPayment

<<

endl;

}Example:

Monetary

Units2021/7/1769This

program

letstheuser

entertheamountindecimal

representing

dollars

and

cents

andoutputareportlistingthe

monetaryequivalentin

singledollars,

quarters,

dimes,

nickels,

and

pennies.Your

program

should

report

maximum

number

ofdollars,

then

the

maximum

number

ofquarters,and

so

on,

inthis

order.Trace

ComputeChangeintremainingAmount

=(int)(amount

*

100);//Find

the

numberofonedollarsint

numberOfOneDollars

=

remainingAmount

/

100;remainingAmount

=

remainingAmount

%100;//Findthe

numberofquarters

inthe

remaining

amountint

numberOfQuarters

=remainingAmount

/25;remainingAmount

=

remainingAmount

%25;//

Findthe

numberof

dimesin

the

remaining

amountint

numberOfDimes

=

remainingAmount

/10;remainingAmount

=

remainingAmount

%10;//

Find

the

number

of

nickels

in

the

remaining

amountintnumberOfNickels

=

remainingAmount

/

5;remainingAmount

=

remainingAmount

%5;//

Findthe

numberof

penniesin

the

remaining

amountint

numberOfPennies=remainingAmount;1156remainingAmountremainingAmountinitialized2021/7/1770Suppose

amount

is

11.56Example:

Displaying

Current

TimeWrite

a

program

that

displays

current

time

in

GMT

in

theformat

hour:minute:second

such

as

1:45:19.The

time(0)

function

in

the

ctime

header

file

returns

thecurrent

ti

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论