C++编程思想 第2卷 第2章 防御性编程

编写完美的软件 对开发者来说可能是一个难以达到的目标,但是应用一些
常规的防御性技术,对于提高代码的质量将会大有帮助

尽管软件产品的复杂性保证了测试人员有做不完的工作,然而,程序设计
人员仍然渴望创建零缺陷的软件

当用户回答猜测结果太大或太小时,出现 新计算出来的子范围不包括秘密
数字
因为一个谎言会导致另一个谎言,最终会使猜数范围缩减到不包含任何数字

//: C02:HiLo.cpp {RunByHand}
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
// Plays the game of Hi-Lo to illustrate a loop invariant.
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;

int main() {
  cout << "Think of a number between 1 and 100" << endl
        << "I will make a guess; "
        << "tell me if I'm (H)igh or (L)ow" << endl;
  int low = 1, high = 100;
  bool guessed = false;
  while(!guessed) {
    // Invariant: the number is in the range [low, high]
    if(low > high) {  // Invariant violation
      cout << "You cheated! I quit" << endl;
      return EXIT_FAILURE;
    }
    int guess = (low + high) / 2;
    cout << "My guess is " << guess << ". ";
    cout << "(H)igh, (L)ow, or (E)qual? ";
    string response;
    cin >> response;
    switch(toupper(response[0])) {
      case 'H':
        high = guess - 1;
        break;
      case 'L':
        low = guess + 1;
        break;
      case 'E':
        guessed = true;
        break;
      default:
        cout << "Invalid response" << endl;
        continue;
    }
  }
  cout << "I got it!" << endl;
  getchar();
  return EXIT_SUCCESS;
} ///:~

表达式if(low > high)可以发现违反不变量条件的情况,如果用户总是说
实话,那么在用完这些猜测前总能找到这个秘密数字

标准C的技术通过从 main()函数中返回不同的值来向调用者报告程序的
状态

输出
Think of a number between 1 and 100
I will make a guess; tell me if I'm (H)igh or (L)ow
My guess is 50. (H)igh, (L)ow, or (E)qual? h
My guess is 25. (H)igh, (L)ow, or (E)qual? h
My guess is 12. (H)igh, (L)ow, or (E)qual? h
My guess is 6. (H)igh, (L)ow, or (E)qual? h
My guess is 3. (H)igh, (L)ow, or (E)qual? h
My guess is 1. (H)igh, (L)ow, or (E)qual? h
You cheated! I quit

Think of a number between 1 and 100
I will make a guess; tell me if I'm (H)igh or (L)ow
My guess is 50. (H)igh, (L)ow, or (E)qual? l
My guess is 75. (H)igh, (L)ow, or (E)qual? l
My guess is 88. (H)igh, (L)ow, or (E)qual? l
My guess is 94. (H)igh, (L)ow, or (E)qual? l
My guess is 97. (H)igh, (L)ow, or (E)qual? l
My guess is 99. (H)igh, (L)ow, or (E)qual? l
My guess is 100. (H)igh, (L)ow, or (E)qual? l
You cheated! I quit

Think of a number between 1 and 100
I will make a guess; tell me if I'm (H)igh or (L)ow
My guess is 50. (H)igh, (L)ow, or (E)qual? l
My guess is 75. (H)igh, (L)ow, or (E)qual? e
I got it!

猜你喜欢

转载自blog.csdn.net/eyetired/article/details/81585423