2014-09-12 203 views
0

我刚开始用Standford课程学习Java。正如你可能知道的每一章都教你如何创建程序来解决问题。我总是倾向于通过根据我们在课程中获得的内容创建新问题来多练习一点。
作为im学习声明我试图创建一个程序,乘n 10次。所以这将是n * n * n ...等等......
它可以工作,但我想知道是否有更简单的方法来解决这个问题。 这是我的代码。Java中乘以10次(初学者)

/*This program multiplies an n number 10 times. 
* 
*/ 

import acm.program.ConsoleProgram; 

public class LiftOff extends ConsoleProgram { 

    public void init() { 
     setSize(height,width); 
    } 

    private static final int height = 600; 
    private static final int width = 600; 

    public void run() { 
     println ("This program multiplies a number 10 times"); 
     double x= readInt("Number: "); 

     double stop = x * x * x * x * x * x * x * x * x * x * x; 

     for (double x1 = x ; x1 <= stop; x1*= x) { 
      println (x1); 
     } 

     println("Done"); 
    } 
} 

我使用双打因为int会消极。我试图让双停= xE + 10,但它不起作用。除此之外的任何解决方案都基于迄今为止所了解的内容。考虑到这个使用acm库。

谢谢。

+0

你可以在[Code Review](http://codereview.stackexchange.com/)上发表。 *代码审查是一个问题和答案网站,用于分享您正在从事的项目的代码 * – Kara 2014-09-12 17:22:46

+1

如果输入足够大,请考虑使用'long'或'BigInteger'。 – user1071777 2014-09-12 17:24:18

+1

这相当于将数字提高到第10次方,并且java.lang.Math中内置了一个方法来完成此操作(对于某些问题域它是一个常见操作):Math.pow(number,10); – Durandal 2014-09-12 17:24:47

回答

1

只需从19循环,每次乘以初始值x本身。

double x= readInt("Number: "); 
double result = x; 

for(int i = 1; i <= 9; i++) 
    result *= x; 
+0

您正在使用x而不是i作为变量。 “int i = 1”是正确的语法 – dganesh2002 2014-09-12 17:25:44

+1

是啊谢谢指出。速度受害者:P。我纠正了它 – qbit 2014-09-12 17:26:48

+0

这很像一个魅力,非常感谢。 – Guillermo 2014-09-12 19:39:46

0
double number = 5; //readDouble("Number: "); 
    double total = number; // == number*1 
    for (int i = 0; i < 9; i++) 
     total = total * number; 
    System.out.println(total); 
0

您计算结果两次(第一次与停止)。如果你想计算n^1000,你会怎么做?有简单得多:

int pow = 10; 
int n = 3; 
int res = 1; 
for (int i=0 ; i<pow ; i++) 
    res *= n; 

它可能是一个有点先进的初学者,但你可能有兴趣知道,有更快的方法来计算^ B。看看fast exponentiation