[英]C++ - for loop not running
Have a very simple code that I'm building in C++. 有一个我用C ++构建的非常简单的代码。 This is my first C++ code so I'm not entirely sure of syntax in some places. 这是我的第一个C ++代码,因此我不能完全确定某些地方的语法。 However, for the following code, my for loop isn't running at all! 但是,对于以下代码,我的for循环根本没有运行! I can't see why not... Can anyone spot the problem? 我看不出来为什么不...有人能发现问题吗?
#include <cstdlib>
#include <cmath>
using namespace std;
int main () {
/*
* Use values for wavelength (L) and wave number (k) calculated from linear
* dispersion program
*
*/
//Values to calculate
double u; //Wave velocity: d*phi/dx
double du; //Acceleration of wave: du/dt
int t;
//Temporary values for kn and L (taken from linear dispersion solution)
float L = 88.7927;
float kn = 0.0707624;
Note: I've left out variable declarations to save on space. 注意:我省略了变量声明以节省空间。
/*
* Velocity potential = phi = ((Area * g)/omega) * ((cosh(kn * (h + z)))/sinh(kn * h))*cos(k*x - omega * t);
* Velocity of wave, u = d(phi)/dx;
* Acceleration of wave, du = du/dt;
*/
for (t = 0; t == 5; t++) {
cout << "in this loop" << endl;
u = ((kn * A * g)/omega) * ((cosh(kn * (h + z)))/sinh(kn * h)) * cos(omega * t);
du = (A * g * kn) * ((cosh(kn * (h + z)))/sinh(kn * h)) * sin(omega * t);
cout << "u = " << u << "\tdu = " << du << endl;
}
cout << L << kn << endl;
return 0;
}
I've put the "in this loop" as a test and it doens't enter the loop (compiles fine).. 我已经将“在此循环中”作为测试,它没有进入循环(编译良好)。
Thanks in advance for taking a look at this! 在此先感谢您看一下!
t
is initialized to 0
, t == 5
will always be evaluated to be false , so your for loop will never run. t
初始化为0
, t == 5
将始终被评估为false ,因此您的for循环将永远不会运行。
update 更新
for (t = 0; t == 5; t++) {
to 至
for (t = 0; t < 5; t++) {
for Statement 声明
Executes a statement repeatedly until the condition becomes false . 重复执行一条语句,直到条件变为false为止。
for ( init-expression ; cond-expression ; loop-expression ) for(init-expression; cond-expression ; loop-expression)
statement;
Should be: 应该:
for (t = 0; t < 5; t++)
The syntax of for loop in C++ is: C ++中for循环的语法为:
for ( init-expression ; cond-expression ; loop-expression )
statement;
The statement executes only while cond-expression is true and in your case it is never true. 该语句仅在cond-expression为true时执行,而在您的情况下则永远为true。
That's simple: the condition for your for
loop is t == 5
- it only loops as long as t
is five, but since you set t = 0
at first, it doesn't loop even once. 这很简单: for
循环的条件是t == 5
仅在t
为5时才循环,但是由于首先设置t = 0
,所以它甚至不会循环一次。 I think t < 5
is what you want. 我认为t < 5
是您想要的。
Please look at the condition expression for for loop . 请查看for循环的条件表达式 。 Hint : You initialized t to 0. 提示 :您已将t初始化为0。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.