gpt4 book ai didi

Java For 循环模式

转载 作者:行者123 更新时间:2023-11-29 03:05:26 25 4
gpt4 key购买 nike

正在做一些 Java 实践和一个特定的 for 循环模式让我感到困惑。我正在努力实现打印此图案的目标,

123456
12345
1234
123
12
1

给出的解决方案是

    for(int k = 8; k > 1; k--) {
for(int l = 1; l < k - 1; l++){
System.out.print(l);
}
System.out.println();
}

我玩过这些值,但我不明白 k = 8 的值。这是否意味着当 k > 1 为真时循环运行 7 次?

edit 我研究了代码,发现了一个对我来说更有意义的更简洁、更简化的代码,

    for(int k = 6; k >= 0; k--) {
for(int l = 1; l < k; l++){
System.out.print(l);
}
System.out.println();
}

它也给了我同样的结果。这样的逻辑是更容易让人迷惑还是更容易理解?

最佳答案

I played with the values but I didn't understand the value of k = 8. wouldn't that mean the loop runs 7 times when k > 1 is true?

我的意思是,只要 k > 1 为真,循环就会运行,但是 k 也减 1,因此循环运行 7 次 但在最后一次运行中它只会打印一个换行符(你没有在你的输出中包含它但它在那里,相信我)。

关于Java For 循环模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32422061/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com