基本上我的教授用另一种方式编码,但我的也能用。我只想问一下我的代码中有没有什么我不明白的隐患?如果基本上是一样的(我猜是这样),我就按我的方法做。
我的代码
int current=0, next =1, temp;
for(int i=0;i<number;i++){
temp = current;
current = next;
next +=temp;
}
return current;
}
教授代码
int current=0, next =1, temp;
for(int i=0;i<number;++i){
temp = next+current;
current = next;
next =temp;
}
return current;
}
一般来说,编译器会很好地生成最佳的汇编,所以我建议用最易读的方式写你的代码。
这里有一种写法,应该是相当可读的。
int current = 0, next = 1;
for(int i = 0; i < number; ++i )
current = std::exchange(next, current + next);
return current;
一旦你明白了如何 std::exchange
工作,这应该更清楚了。例如,没有必要使用 temp
变量。
两种实现在功能上是相同的,只要使用你认为更易读的那一种即可。