加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C中的递减运算符

发布时间:2020-12-16 10:41:04 所属栏目:百科 来源:网络整理
导读:我来自C背景,现在我正在使用C学习OOP 以下是计算阶乘的程序. #include iostreamusing namespace std;void main (){ char dummy; _int16 numb; cout "Enter a number: "; cin numb; double facto(_int16); cout "factorial = " facto(numb); cin dummy;}doubl
我来自C背景,现在我正在使用C学习OOP

以下是计算阶乘的程序.

#include <iostream>

using namespace std;

void main ()
{
    char dummy;
    _int16 numb;
    cout << "Enter a number: ";
    cin >> numb;

    double facto(_int16);

    cout << "factorial = " <<facto(numb);
    cin >> dummy;
}

double facto( _int16 n )
{
    if ( n>1 )
        return ( n*facto(n-1) );
    else
        return 1;
}

上面的代码工作正常.

但是如果我替换return语句

return ( n*facto(n-1) );

有了这个

return ( n*facto(n--) );

那它不起作用. n–不会将n递减1.为什么?

我正在使用Visual Studio 2012

编辑:知道了!谢谢 :)
*另外,我想补充下面的答案:使用–n将导致n在语句执行之前递减.因此,由于预先递减,表达式将变为(n-1)* facto(n-1).这就是为什么在这种情况下最好不要使用预减量*

解决方法

编辑::下面的解释只是为了阐明后期和减少前的使用,以便OP更好地理解它们. OP代码的正确答案是,n * facto(n – 1). @OP:你不应该在代码的那一部分做任何预先减少,因为它会因为对变量n的无序修改而调用未定义的行为.

前后减少::
如果要在传递值之前递减变量,则必须使用预递减(wiki-link).另一方面,后递减在变量递减之前计算表达式:

int n = 10,x;
x = --n;                // both are 9

int n = 10,x;
x = n--;                // x = 10,i = 9

为什么不在你的情况下使用预减量?:: n * facto(n–)导致UB.
为什么?

The Standard in §5/4 says

Between the previous and next sequence point a scalar object shall
have its stored value modified at most once by the evaluation of an
expression.

The prior value shall be accessed only to determine the value to be
stored.

这意味着,在两个序列点之间,变量不能被多次修改,如果一个对象被写入一个完整的表达式,那么在同一个表达式中对它的任何和所有访问都必须直接参与值的计算.要写.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读