Java 如何显示数字的立方体的总和?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19570048/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to display the sum of the cubes of the digits?
提问by name123
Code:
代码:
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;
}
}
}
Output:
输出:
Enter a Number
**223**
Cube of 3 is 27
Cube of 2 is 8
Cube of 2 is 8
How do I add the cubes of these numbers? For example, 27+8+8 would be 43
我如何添加这些数字的立方体?例如,27+8+8 就是 43
采纳答案by Svend Hansen
Maybe you want to do something like this:
也许你想做这样的事情:
int number = input;
int sum = 0;
while (number > 0) {
int digit = number % 10;
sum += digit * digit * digit;
number /= 10;
}
回答by Fedy2
Here a solution:
这里有一个解决方案:
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);
回答by But I'm Not A Wrapper Class
You seem new to Java, so here is a more simple (and readable) example for you:
您似乎对 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);
}
}
You want to get each number individually then create the result.
您想单独获取每个数字,然后创建结果。
Sample input:
样本输入:
2
2
3
Output should be:
输出应该是:
43
回答by sareeshmnair
Try this code.
试试这个代码。
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);