正整数乘以负值 [英] Positive integers that multiply to a negative value

查看:252
本文介绍了正整数乘以负值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过阅读Stroustrup的使用C ++的原理和实践来学习C ++。

I am learning C++ by reading Stroustrup's "Principles and Practice Using C++".

在关于前后条件的部分中,有以下函数示例:

In the section about pre- and post-conditions there is the following example of function:

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

    int a = length*width;

    if (a<=0) 
        error("area() post-condition");

    return a;
}

令我困惑的是关于此代码的任务:

What confused me is the task about this code:


查找一对值,以便此版本
区域的前提条件成立,但后置条件不存在。

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

是否存在这样的可能整数值,前提条件是好的但条件不是吗?

Are there such possible values for integer that pre-conditions is ok but post-condition not?

推荐答案


是否存在这样的可能整数值,前提条件是否正常但后置条件不是?

Are there such possible values for integer that pre-conditions is ok but post-condition not?

是的,有许多输入值,可能导致后置条件失败。例如。

Yes there's a number of input values, that can cause the post condition to fail. If e.g.

int a = length*width;

溢出正 int 范围( std :: numeric_limits< int> :: max())并且编译器实现在这种情况下产生负值。

overflows the positive int range (std::numeric_limits<int>::max()) and the compiler implementation yields a negative value for this case.

正如其他人在答案中指出的那样, length * width 的情况超出了的界限0-std :: numeric_limits< int> :: max()[实际上是未定义的行为,并且post条件呈现仅仅是无用的,因为可能需要任何值a

As others noted in their answers, the situation that length*width goes out of bounds from ]0-std::numeric_limits<int>::max()[ is actually undefined behavior, and the post condition renders merely useless, because any value might need to be expected for a.

解决此问题的关键点在 @ Deduplicator 答案,前提条件需要改进。

The key point to fix this, is given in @Deduplicator's answer, the pre-condition needs to be improved.

作为Bjarne Stroustrup给出这个例子的理由的长矛:

As a lance for Bjarne Stroustrup's reasonings to give that example:

我想他想指出这种不确定的行为可能会导致意外的消极后置条件中的值和在前置条件下检查的天真假设的惊人结果。

I assume he wanted to point out that such undefined behavior might lead to unexpected negative values in the post-condition and surprising results for a naive assumption checked with the pre-condition.

这篇关于正整数乘以负值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆