代码:
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
答案 0 :(得分:2)
也许你想做这样的事情:
int number = input;
int sum = 0;
while (number > 0) {
int digit = number % 10;
sum += digit * digit * digit;
number /= 10;
}
答案 1 :(得分: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);
答案 2 :(得分: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);
答案 3 :(得分: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