这可能是一个愚蠢的问题,但我无法弄清楚。它与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,但它一定是出于另一个原因。因为我刚刚检查过,没有区别。感谢您的耐心和时间,我只是希望我知道我做了什么!
答案 0 :(得分:5)
如果你在没有作业的情况下增加,没有区别。但是,在以下情况下,有:
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可以帮助你。
答案 1 :(得分:4)
n++
和++n
之间的唯一区别是n++
产生原始值n
,++n
产生n
的值在它增加之后。两者都有通过递增来修改n
的值的副作用。
如果结果被丢弃,就像你的代码中那样,没有有效的区别。
如果你的程序表现不同,取决于你是否写
n++;
或
++n;
它必须是出于其他原因。
事实上,当我在我的系统上编译和执行你的程序时,我在两种情况下都得到完全相同的输出。在输出格式中添加换行符,我得到:
At n = 25, Algorithm A performs in 114661785600 seconds &
Algorithm B performs in 282429536481 seconds.
你还没有告诉我们你得到了什么输出。请更新您的问题以显示两种情况下的输出。
答案 2 :(得分:0)
前缀版本(++ n)改变变量,然后传递其值。 后缀版本(n ++)传递当前值,然后更改变量。