这可能是个愚蠢的问题,但我就是想不通。它与 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++,我会得到错误的答案。谁能解释一下为什么?
编辑:好吧,它用++n 显示 24,用 n++ 显示 25,但这一定是出于其他原因。因为我现在刚查过,没有区别。感谢你们的耐心和时间,我只希望我知道我做了什么!
最佳答案
如果你在没有赋值的情况下递增,没有区别。但是,在以下情况下,有:
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可以帮助你。
关于c - while循环结束时n++和++n的区别? (美国标准 C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25705000/