如何打印每个整数的倒数第二位的总和?
在以下程序中(因此,将打印8,因为1 + 3 + 4为8):
import java.util.*;
public class Pr6{
public static void main(String[] args){
Scanner scan = new Scanner (System.in);
int num1;
int num2;
int num3;
int sumSecToLast;
System.out.print("Please write an integer: ");
num1 = scan.nextInt();
System.out.print("Please write an integer: ");
num2 = scan.nextInt();
System.out.print("Please write an integer: ");
num3 = scan.nextInt();
sumSecToLast = (num1/10) % 10 + (num2/10) % 10 + (num3/10) % 10;
System.out.print((num1/10) % 10 + " + " + (num2/10) % 10 + " + " + (num3/10) % 10 + " = " + sumSecToLast);
}//main
}//Pr6

答案 0 :(得分:1)
num1 % 10
是最后一位数
(num1/10) % 10
是倒数第二位。
因此,如果要计算3个输入整数的倒数第二个数字的总和,请将代码更改为:
sumLastD = (num1/10) % 10 + (num2/10) % 10 + (num3/10) % 10;
答案 1 :(得分:1)
@Bader,试试这个代码..会工作......
Scanner scan = new Scanner (System.in);
int num1;
int num2;
int num3;
int sumLastD;
System.out.print("Please write an integer: ");
num1 = scan.nextInt();
System.out.print("Please write an integer: ");
num2 = scan.nextInt();
System.out.print("Please write an integer: ");
num3 = scan.nextInt();
System.out.println(num1+" -- "+num2+" -- "+num3);
int divideBy1 = 0;
int divideBy2 = 0;
int divideBy3 = 0;
if(num1>10 && num1<100)
divideBy1=10;
else if(num1>100 && num1<1000)
divideBy1=100;
if(num2 >10 && num2<100)
divideBy2=10;
else if(num2>100 && num2<1000)
divideBy2=100;
if(num3>10 && num3<100)
divideBy3=10;
else if(num3>100 && num3<1000)
divideBy3=100;
int ans1=0,ans2=0,ans3=0;
if(num1<10)
ans1=num1;
else
ans1=num1 % divideBy1;
if(num2<10)
ans2=num2;
else
ans2=num2% divideBy2;
if(num3<10)
ans3=num3;
else
ans3=num3 % divideBy3;
sumLastD = ans1+ans2+ans3;
System.out.println("Total = " + sumLastD);
答案 2 :(得分:-2)
如果你的意思是所有3个整数的总和,你的公式应该是这样的。
sumLastD = num1 + num2 + num3;
如果这不是你的意思,抱歉,但你的问题有点模糊。