java For 循环乘数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36516377/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
For Loop Multiplying Number
提问by hama
I need some help -
我需要一些帮助 -
At the end of a for loop, I need to set an original value to the next multiple of the value.
在 for 循环结束时,我需要将原始值设置为该值的下一个倍数。
This is what I have so far -
这是我到目前为止 -
int originalNumber = 1;
for (int i = 1; i <= 10000; i++) {
originalNumber *= i;
}
However, this code will not find the multiples of 1; as the multiples of 1 should be (1, 2, 3, 4, 5, 6, ... ...)
但是,这段代码不会找到 1 的倍数;因为 1 的倍数应该是 (1, 2, 3, 4, 5, 6, ... ...)
This code that I have written will be (1, 1, 2, 6, 24) etc;
我编写的这段代码将是 (1, 1, 2, 6, 24) 等;
What is a good way to get the multiples (inside of the loop)?
获得倍数(在循环内)的好方法是什么?
回答by Jon Skeet
You don't need to change originalNumber
at all - just multiply i
by originalNumber
:
你不需要改变originalNumber
在所有-只是乘i
由originalNumber
:
int originalNumber = 1;
for (int i = 1; i <= 10000; i++) {
int multiple = originalNumber * i;
// Use multiple however you want to
}
To get all the multiples of 2, you'd set originalNumber
to 2, etc.
要获得 2 的所有倍数,您需要设置originalNumber
为 2,依此类推。
回答by Roman ?omowski
You ask for version without additional variable:
您要求没有附加变量的版本:
int originalNumber = 1;
for (int multiple = originalNumber; multiple <= 10000; multiple += originalNumber) {
// Use multiple however you want to
}
回答by Sean
int n = scanner.nextInt();
for (int i = 1; i <= 10; i++){
int multiple = i * n;
System.out.println(n + " x " + i + " = " + multiple);
}
You can try this code, it prints any multiple till 10;
Your Output (stdout)
2 x 1 = 2
2 x 2 = 4
...
2 x 10 = 20
你可以试试这个代码,它打印到 10 的任意倍数;你的输出 (stdout) 2 x 1 = 2
2 x 2 = 4 ... 2 x 10 = 20