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版)

5.8 估计

想象一下,你已经写了一个进行简单计算的程序,例如计算六边形面积。运行这个程序你得到的结果是-34.56。你知道它肯定有问题,为什么?因为面积不可能是负数。接下来,你找到并修改了相应错误(不管它是什么),然后再次得到一个结果21.65685。这一次对了么?它很难说,因为我们一般不能马上说出计算六边形的公式。为了避免将一个产生可笑结果的程序交付用户而使我们出丑,我们应该在交付之前检查程序结果是否合理。在本例中,这个工作很简单。六边形与正方形很接近。在纸上画一个六边形,目测一下,它接近一个3乘3的正方形。这样一个正方形的面积是9。真倒霉,结果21.65685不可能是对的。因此我们继续修改程序,新程序的计算结果10.3923。这一次,它可能是正确的了!

这种方法与六边形无关,其关键思想是,除非我们知道正确的结果大概是什么,或者与什么比较类似,否则我们不能判定得到的结果是否合理。要不断问自己如下问题:

1.这个问题的答案合理么?

还应该问一个更一般的(通常也更难)问题:

2.我们应该如何判定一个结果是否合理?

这里,我们没有问“最准确的答案是什么?”或“正确答案是什么?”这是我们编写的程序要告诉我们的。我们所要知道的就是这个答案是合理的。只有确定了结果的合理性后,我们才能做下一步工作。

估计(estimation)是一种优雅的艺术,它将常识与一些用来解决常见问题的非常简单的数学方法结合起来。一些人很擅长在头脑中估计,但我们更提倡“在信封背面”随意写写画画,因为这种方法能够帮助我们减少错误。我们这里所说的估计是一种非正式的技术。有时候它会被(幽默地)称为瞎估计(guesstimation),因为它是将一点猜测和一点计算结合起来的方法。

试一试

我们的六边形的每边长都是2厘米。得到的结果是正确的吗?亲自动手“在信封背面”算一下。在纸上把它画出来,不要觉得这太简单了。许多著名的科学家都有这样一种令人敬佩的能力:用一支笔在信封背面(或餐巾纸上)估计出问题的近似结果。这是一种能力,实际也是一种简单的习惯,它能够帮助我们节省很多时间,减少很多错误。 ...

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