gpt4 book ai didi

c++ - C++ 中的前置条件和后置条件

转载 作者:太空宇宙 更新时间:2023-11-04 16:11:17 25 4
gpt4 key购买 nike

毕竟,我们通常必须说明函数返回的内容;也就是说,如果我们从函数返回一个值,我们总是对返回值做出 promise (否则调用者会期望什么)。

int area(int lenght, int width)
// pre-conditions : lenght and width are positive
// post-condition : returns a positive value that is the area
{
if (lenght <= 0 || width <= 0) error("area() pre-condition");
int a = lenght * width;
if (a <= 0) error("area() post-condition");
return a;

}

这是一个使用前置条件和后置条件的简单示例,但我无法理解的是作者在展示示例后所说的内容:

"We couldn't check the complete post-condition, but we checked the part that said that it should be positive".

这是什么意思?为什么我们不能检查完整的后置条件?根据我的理解,在这种情况下,作为后置条件,我们只需要检查变量 a 是否为正,我错了吗?

作者问我这个问题:

Find a pair of value so that the pre-condition of this version of area holds, but the post-condition doesn't.

不是不可能吗??

最佳答案

In my understanding in this case as post-condition we just need to check that the variable a is positive, am I wrong ?

是的。注意完整的后置条件...

returns a positive value that is the area

可以传递 lengthwidth 的值,这样 a 就不会因为溢出而到达正确的区域。

关于c++ - C++ 中的前置条件和后置条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28416392/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com