如果其索引是3的倍数,则尝试输出beta组件的值。我在for循环中设置条件,但它只在索引0处打印组件。在for循环条件中是否允许这样做?我真的需要在循环中使用if语句吗?
谢谢。
double beta[20] = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20 };
cout << fixed << showpoint << setprecision(2);
for (int index = 0; index < 20 && index % 3 == 0; index++)
cout << beta[index] << endl;
当条件为假时,循环停止。对于index == 1
,条件是错误的。
如果您想要一个跳过迭代的循环,请在循环体中使用if
。
但是对于这个简单的情况,最好在每次迭代时将index
增加3。
你的循环的条件是:index < 20 && index % 3 == 0
这个条件在index = 1
是假的,所以循环停止。为了完成这项工作,将条件分为两部分。如果for
和一个在if
放一个。以下是代码:
double beta[20] = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20 };
cout << fixed << showpoint << setprecision(2);
for (int index = 0; index < 20 ; index++){ // First condition
if (index % 3 == 0){ // Second condition
cout << beta[index] << endl;
}
}
希望有所帮助!
如果你试图计算1 mod 3
它将等于1,因为第二个条件将是假的,所以程序将在index = 0
(remainder = 0 here
)之后执行主体,从1开始之后你永远不会进入for循环体。希望有所帮助。
这个简短的答案在for循环条件下做了什么呢?
for (int index = 0; ((index % 3) == 0 || (index++ && index++)) && index < 20 ; index++)
cout << beta[index] << endl;
不要忘记我们在条件结束时放置index < 20
。