Skip to Content
C++程序设计:原理与实践(基础篇)(原书第2版)
book

C++程序设计:原理与实践(基础篇)(原书第2版)

by 本贾尼 斯特劳斯特鲁普
August 2021
Intermediate to advanced
450 pages
9h 36m
Chinese
Pearson
Content preview from C++程序设计:原理与实践(基础篇)(原书第2版)

4.3.3 类型转换

表达式中允许存在不同的数据类型。例如,2.5/2是一个double类型除以一个int类型。这表示什么呢?我们应该做整型除法还是双精度浮点型除法呢?整型除法时余数被丢弃,例如5/2的结果为2。浮点型除法时余数被保留,例如5.0/2.0是2.5。“2.5/2是整型除法还是浮点型除法?”的答案是“浮点型除法,因为整型除法会丢失余数”。也就是说,2.5/2的结果是1.25而不是1。我们遵循这样的规则:如果算术表达式中有double类型数据的话,就进行浮点型算术计算,结果为double类型;否则就使用整型算术计算,结果为int类型。例如:

记号type(value)和type{value}表示“将value转换为type类型,就像用值value来初始化type类型的变量一样”。这意味着,编译器会把上述运算中的int自动转换为double,或将char自动转换为int。使用type{value}可避免窄化转换(3.9.2节),而type(value)不能。在运算完成的时候,编译器可能还得再进行一次转换,以用来作为初始化值或赋值语句的右端项。例如:

需要特别注意浮点运算表达式中的整数除法。例如,摄氏温度与华氏温度的转换公式为:f=9/5×c+32,程序代码如下:

不幸的是,上述程序不能正确实现摄氏温度与华氏温度的转换功能,因为9/5的值是1而不是我们期望的1.8。如果要达到我们期望的结果,必须将9或5(或者两者)转换为double类型。 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

C++语言导学(原书第2版)

C++语言导学(原书第2版)

本贾尼 斯特劳斯特鲁普
管理Kubernetes

管理Kubernetes

Brendan Burns, Craig Tracey
Python编程入门与实战

Python编程入门与实战

Posts & Telecom Press, Fabrizio Romano

Publisher Resources

ISBN: 9787111562252