-3

代码:

import java.util.*;
import java.io.*;

class Cubesum {
public static void main(String args[]){
    int input=0;
    int num1,num2,num3;

    //read the number
    System.out.println("Enter a Number");
    Scanner console = new Scanner(System.in);
    input= Integer.parseInt(console.nextLine());

    // now let us print the cube of digits
    //i.e if number is 123 we will print 1^3, 2^3 and 3^3
    //we will also add 1 and 3 to output the sum of first
    //and last digits
    int number = input; //number is a temp variable
    int counter = 0; //counter is used to count no of digits

    while(number>0){
        int t= number%10;
        System.out.println("Cube of "+t +" is "+(t*t*t));
        counter = counter+1;
        number = number/10;

    }


}
}

输出:

Enter a Number
**223**
Cube of 3 is 27
Cube of 2 is 8
Cube of 2 is 8

如何添加这些数字的立方体?例如,27+8+8 将是 43

4

4 回答 4

2

也许你想做这样的事情:

int number = input;
int sum = 0;
while (number > 0) {
    int digit = number % 10;
    sum += digit * digit * digit;
    number /= 10;
}
于 2013-10-24T15:28:08.567 回答
2

试试这个代码。

int sum=0;
while(number>0){
    int t= number%10;
    System.out.println("Cube of "+t +" is "+(t*t*t));
    sum=sum+(t*t*t);
    counter = counter+1;
    number = number/10;

}
System.out.println(sum);
于 2013-10-24T15:32:47.723 回答
1

这里有一个解决方案:

int sum = 0;
while(number>0){
  int t= number%10;
  System.out.println("Cube of "+t +" is "+(t*t*t));
  sum += t*t*t;
  counter = counter+1;
  number = number/10;
}
System.out.println(sum);
于 2013-10-24T15:27:55.213 回答
1

您似乎对 Java 很陌生,所以这里有一个更简单(且易读)的示例:

import java.util.*;
import java.io.*;

class Cubesum {
public static void main(String args[]){

    int num1,num2,num3;
    Scanner console = new Scanner(System.in);

    //read the numbers
    System.out.println("Enter the first number");
    num1 = Integer.parseInt(console.nextLine());
    System.out.println("Enter the second number");
    num2 = Integer.parseInt(console.nextLine());
    System.out.println("Enter the third number");
    num3 = Integer.parseInt(console.nextLine());

    int output = (int1*int1*int1)+(int2*int2*int2)+(int3*int3*int3)
    System.out.println("result is:  " + output);


}
}

您想单独获取每个数字,然后创建结果。

样本输入:

2

2

3

输出应该是:

43
于 2013-10-24T15:29:47.830 回答