[英]Input any number and print all the odd number in descending order using while loop
How do i print all odd number in descending order?如何按降序打印所有奇数?
int a = in.nextInt();
int counter = 0;
while(counter < a){
if ((counter % 2) != 0){
System.out.println(counter);
}
counter--;
}
input: 10 Expected output: 9 7 5 3 1输入:10 预期输出:9 7 5 3 1
You can create an array of numbers, then sort it.您可以创建一个数字数组,然后对其进行排序。 add numbers to an array instead of printing numbers.将数字添加到数组而不是打印数字。 Then sort the array.然后对数组进行排序。 Then use a foreach
to print all.然后使用foreach
打印所有内容。
use a for loop:使用 for 循环:
int a = in.nextInt();;
for(int i = a; i > 0; i--) {
if(i % 2 != 0) {
System.out.println(i);
}
}
Use this用这个
int a = in.nextInt();
while(a > 0){
if ((a % 2) != 0){
System.out.println(a);
}
a--;
}
No need you use counter不需要你使用计数器
int a = 10;
while(a!=0){
if ((a % 2) != 0){
System.out.println(a);
}
a--;
}
How about:怎么样:
int a = in.nextInt();
if (a % 2 == 0) a--;
while (a > 0) {
System.out.println(a);
a -= 2;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.