作为一个例子,在开始时有很多ifs 和很多else if在一个之后if。我在下面添加了一些伪代码。
if (x=1)
print x;
if (x=2)
print x;
if (x=3)
print x;
Run Code Online (Sandbox Code Playgroud)
或者
if (x=1)
print x;
else if (x=2)
print x;
else if (x=3)
print x;
Run Code Online (Sandbox Code Playgroud)
你的代码无法编译;如果你真的想检查你需要使用的条件,==而不是 for =; 不仅仅是效率,这两种技术的使用取决于要求。您可以将第一种情况用于以下场景:
if (x==1)
//Do something
// 'x' may change here
if (x==2) // check for next condition
// Do another thing
// 'x' may change
if (x==3) // check for another condition
// Do something more
//'x' may change
Run Code Online (Sandbox Code Playgroud)
如果 for 的值x没有变化,您可以执行第二组代码。这样您就可以在找到真实条件后跳过对其余条件的评估。考虑x=1所以它不会检查x==2并且x==3这样我们可以减少执行时间。
x=1;
if (x==1) // Evaluates to true;
// Do Something
// Exit the if
else if (x==2) // will not check for this
//Do another thing
else if (x==3) // will not check for this
//Do another thing
Run Code Online (Sandbox Code Playgroud)
如果您要检查更多条目,则应使用开关而不是这两个。
| 归档时间: |
|
| 查看次数: |
3087 次 |
| 最近记录: |