在 Programming: Principles and Practice using C++ 的第 5.10.1 章中,有一个“Try this”练习用于调试某个区域的错误输入。前置条件是长度和宽度的输入是否为 0 或负数,而后置条件是检查面积是否为 0 或负数。引用这个问题,“找到一对值,使这个版本的区域的前置条件成立,但后置条件不成立。”。到目前为止的代码是:
#include <iostream>
#include "std_lib_facilities.h"
int area (int length, int width) {
if (length <= 0 || width <= 0) { error("area() pre-condition"); }
int a = length * width;
if(a <= 0) { error("area() post-condition"); }
return a;
}
int main() {
int a;
int b;
while (std::cin >> a >> b) {
std::cout << area(a, b) << '\n';
}
system("pause");
return 0;
}
虽然代码似乎可以工作,但我无法理解哪些输入将使前置条件成功但会触发后置条件。到目前为止,我已经尝试在其中一个输入中输入字符串,但这只是终止程序并尝试查找等同于 0 的 ascii,但结果也相同。这应该是某种技巧问题还是我错过了什么?