变量和运算符综合应用。
int num = 4321; // 整数
int a = num;
int sum = 0; // 数字之和
while( a != 0 ){
sum += a%10;
a /= 10;
}
System.out.print(sum);
import java.util.*;
public class ZhengShu{
private final static Scanner scanner=new Scanner(System.in);
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int num = scanner.nextInt();
System.out.println("请输入一个整数:"+num);
while((num/10)!=0){
sum+=num%10;
num=num/10;
}
sum+=num;
System.out.print("各位数字的和为:"+sum);
scanner.close();
}
}
import java.util.Scanner;
public class dmo {
public static void main(String[]args){
Scanner scanner=new Scanner(System.in);
System.out.println("请输入整数:");
int num=scanner.nextInt();
int sum=num%10;//获取个位
for(int i=10;;){
if(num<10){
break;
}else if(num/i==0){
break;
}else{
sum+=num%(i*10)/i;//获取各位的数字
}
i*=10;
}
System.out.println("各个位数之和为:"+sum);
}
}
public int numAdd(int num){
int sum = 0;
while(num/10 != 0){
sum+=num%10;
num=num/10;
}
sum+=num;
return sum;
}
Scanner sc = new Scanner(System.in); int num = sc.nextInt(); while((num/10)!=10){ sum+=num%10; num=num/10; } sum+=num; //最后还有num的个位数要加 System.out.print("各位数字的和为:"+sum);
System.out.println("合为"+(num%10+num/10%10+num/100%10+num/1000));