【问题标题】:The difference between n++ and ++n at the end of a while loop? (ANSI C)while循环结束时n++和++n的区别? (ANSI C)
【发布时间】:2014-10-31 12:51:48
【问题描述】:

这可能是一个愚蠢的问题,但我就是想不通。它与 n++ 和 ++n 之间的差异有关(我以为我理解但显然不是)。

#include <stdio.h>
#include <math.h>

long algorithmA(int n);
long algorithmB(int n);

int main(){
    long A, B;
    A = B = 0;
    int n = 1;
    while(A >= B){
        A = algorithmA(n);
        B = algorithmB(n);
        n++;
    }
    printf("At n = %d, Algorithm A performs in %ld seconds & "
           "Algorithm B performs in %ld seconds.", n, A, B);

}

long algorithmA(int n){
    return pow(n,4) * 86400 * 4;
}

long algorithmB(int n){
    return pow(3,n);
}

在这里,您可能会知道我正在尝试查看算法 A 在什么时候优于算法 B。函数和时间单位是在作业问题中提供给我的。

无论如何,我一直认为“++”的顺序在 while 循环结束时无关紧要。但是如果我用 ++n 而不是 n++,我会得到错误的答案。谁能解释一下原因?

编辑:嗯,它显示 24 和 ++n 和 25 和 n++,但它一定是出于另一个原因。因为我现在才检查,没有任何区别。感谢你们的耐心和时间,我只是希望我知道我做了什么!

【问题讨论】:

  • 不确定是否直接重复(不同的语言),但我敢打赌问题是一样的。 Is there a difference between x++ and ++x.
  • @mlwn 我认为你搞错了。
  • @Takendarkk 大声笑..刚刚删除它.. :) 输入错误..
  • 单独操作,不使用其“结果”时,没有区别。只有使用结果(如myArray[n++])才会有所不同,而区别在于您是在递增之前还是之后有效地获取数组元素。
  • 这些之间不应该有任何区别,因为增量没有在表达式中使用。你有其他显示的输出吗?

标签: c increment post-increment pre-increment


【解决方案1】:

如果你在没有赋值的情况下递增,没有区别。但是,在以下情况下,有:

int n = 1;
int x = n++; // x will be 1 and n will be 2

在本例中,语句在增量之前执行。

int n = 1;
int x = ++n; // both x and n will be 2

但是,在本例中,增量发生在语句执行之前。

Operator precedence可以帮到你。

【讨论】:

    【解决方案2】:

    n++++n 之间的唯一区别是n++ 产生n 的原始值,而++n 在增加后产生n 的值。两者都有通过增加 n 的值来修改它的副作用。

    如果结果被丢弃,就像在您的代码中一样,则没有有效的区别。

    如果你的程序行为不同,取决于你是否编写

    n++;
    

    ++n;
    

    一定是因为其他原因。

    事实上,当我在我的系统上编译和执行你的程序时,我在两种情况下得到完全相同的输出。在输出格式中添加换行符,我得到:

    At n = 25, Algorithm A performs in 114661785600 seconds &
    Algorithm B performs in 282429536481 seconds.
    

    你还没有告诉我们你得到了什么输出。请更新您的问题以显示两种情况下的输出。

    【讨论】:

      【解决方案3】:

      前缀版本 (++n) 改变变量,然后传递它的值。 后缀版本 (n++) 传递当前值,然后更改变量。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-30
        • 2014-04-20
        • 1970-01-01
        • 2011-04-07
        • 1970-01-01
        相关资源
        最近更新 更多