输入一个整数,判断该数是否为降序数,如果是则输出true,不是则输出false。所谓降序数是指该数的各位数字从高到低逐步下降,包括相等。Java
时间: 2024-02-13 08:07:51 浏览: 66
好的,我来为您编写Java代码来实现该功能:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
boolean isDescending = true;
int prevDigit = 10; // 初始值为10,确保第一位数字一定小于等于10
while (num > 0) {
int digit = num % 10; // 取出个位数字
if (digit > prevDigit) { // 如果当前数字大于上一位数字
isDescending = false; // 不是降序数
break;
}
prevDigit = digit; // 更新上一位数字
num /= 10; // 去掉个位数字
}
System.out.println(isDescending);
scanner.close();
}
}
```
这段代码中,首先使用`Scanner`类获取用户输入的整数。然后使用一个`while`循环,从低位到高位逐一判断每一位数字是否符合条件。如果出现当前数字大于上一位数字的情况,就说明不是降序数,将`isDescending`变量设为`false`,并跳出循环。最后输出`isDescending`变量的值即可。
注意,我们在循环中使用了两个变量`prevDigit`和`digit`,分别表示上一位数字和当前位数字。由于数字中可能含有0,因此我们不能使用初始值为0的方式来初始化`prevDigit`,而应该使用一个比任意一位数字都大的数,例如10。这样可以确保第一位数字一定小于等于`prevDigit`。
阅读全文
相关推荐
















