如何设计一个以 1 开头、以 0 结尾的 int 循环 (1,2,3,4,5,6,7,8,9,0)
我的问题是使用嵌套 for 循环来创建此输出:
| | | | | |
123456789012345678901234567890123456789012345678901234567890
我无法找出用 0 替换 int 10 的最佳方法。我尝试了几种方法,但它们很花哨,而且看起来并不对我来说是对的。我希望我的问题很明显,这很难解释。有人能指出我正确的方向吗?
我已经实现了正确的输出,但有些东西告诉我有更好的方法来解决这个问题。这是我的代码:
int k = 0;
for (int i=1; i<=6; i++){
System.out.print(" |");
}
System.out.println();
for (int m=0; m<6; m++){
for (int j=1; j<10; j++){
System.out.print(j);
}
System.out.print(k);
}
太棒了! Modulo 是我一直在寻找的答案。我对此感觉更舒服:
for (int i=1;i<=6;i++){
System.out.print(" |");
}
System.out.println();
for (int m=0;m<6;m++){
for (int j=1;j<=10;j++){
System.out.print(j % 10);
}
}
My problem is to use nested for loops in order to create this output:
| | | | | |
123456789012345678901234567890123456789012345678901234567890
I can't figure out the best way to replace the int 10 with 0. I've tried a few ways, but they are gimmicky, and don't seem right to me. I hope my problem is apparent, it's kind of hard to explain. Can someone point me in the right direction?
I've achieved the correct output, but something tells me that there is a better way to go about this. Here's my code:
int k = 0;
for (int i=1; i<=6; i++){
System.out.print(" |");
}
System.out.println();
for (int m=0; m<6; m++){
for (int j=1; j<10; j++){
System.out.print(j);
}
System.out.print(k);
}
Great! Modulo was the answer I was looking for. I feel much more comfortable with this:
for (int i=1;i<=6;i++){
System.out.print(" |");
}
System.out.println();
for (int m=0;m<6;m++){
for (int j=1;j<=10;j++){
System.out.print(j % 10);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
使用模运算符 %。它给你剩下的。
因此,从 1 开始循环,当 1 除以 10 时,余数为1。
当 2 除以 10 时,余数为 2,依此类推。当 10 除以 10 时,输出为 0。
Use the modulo operator %. It gives you the remainder.
Therefore starting the loop at 1, when 1 is divided by 10 the remainder is 1.
When 2 is divided by 10 the remainder is 2, etc.. When 10 is divided by 10 the output is 0.
您需要 mod 运算符 (
%
)。它计算除法后的余数。
You want the mod operator (
%
).It calculates the remainder after division.
为什么你不能生成这个:
然后将角色从前面取下来并将其粘在末端?
Why can't you just generate this:
And then take the character off the front and stick it on the end?
有很多方法。最简单的可能是:
如果你有 2 个循环,那么你可以使用这个事实:
There are many ways. The simplest is this, probably:
If you have 2 loops, then you can use this fact:
如果这代表一种模式,那么虽然不是简单地定义模式然后将结果输出到屏幕(或执行任何您想要的操作),但它是:
If this represents a kind of pattern, then while not simply define the pattern and then output the result to the screen (or do whatever you want), it is:
这是一个非模解:
是的,是的,我知道它很便宜。不过它会起作用的。 ;)
Here's a non-modulo solution:
Yea, yea, I know it's cheap. It'll work though. ;)
您可以尝试使用模数:
You could try using modulo: