[英]Is using a for-loop “creatively” frowned upon? [on hold]
Given following task:给定以下任务:
Add 6 to a number that's starting at 7 until it's bigger than 30 and print out how often you've added the number 6 to it at the end.
将 6 添加到从 7 开始直到大于 30 的数字,并打印出您在末尾添加数字 6 的频率。
I came up with following solution:我想出了以下解决方案:
int num = 7, i = 0;
for(; num <= 30; ++i) {
num += 6;
}
System.out.println("Added " + i + " times the number 6 to 7");
Is using a for-loop in such a way bad practice?以这种方式使用for循环是不好的做法吗?
I'm not sticking to the "traditional" way a for-loop is implemented.我不坚持实现 for 循环的“传统”方式。
There are actually use cases for defining a value outside of the for-loop block, such that if you need to retain that value after the computation.实际上存在用于在 for 循环块之外定义值的用例,例如,如果您需要在计算后保留该值。
That being said, if you don't need 'num' or 'i' after the for-loop, then yeah this would definitely be unconventional (not necessarily frowned upon, thats a bit subjective).话虽如此,如果您在 for 循环之后不需要 'num' 或 'i',那么是的,这肯定是非常规的(不一定不赞成,这有点主观)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.