2013-02-18 20 views
0

我已經設法做了這個問題的一部分,但我有一個問題的立方體方法。 我需要從cube方法中調用square方法來返回多維數據集結果。 例如:若要將數字5平方,結果將爲25.然後,我將此方法稱爲立方體方法以返回答案125.有人可以告訴我哪裏出錯了嗎?創建兩個方法接受一個數字作爲參數,一個方格的數字和一個多維數據集

這裏是我的代碼:

import java.util.*; 
public class ExamPaper2011 
{ 
public static void main(String [] args){ 

    int totalSquared = 0; 
    int totalCubed = 0; 

    cubedNumber(totalSquared, totalCubed); 
} 

public static int squaredNumber(int totalSquared){ 

    Scanner in = new Scanner(System.in); 

    System.out.print("Please enter a number to square: "); 
    int numSquare = in.nextInt(); 
    System.out.println("You entered " + numSquare); 
    totalSquared = (int) Math.pow (numSquare, 2); 
    System.out.println("The number squared is " + totalSquared); 
    return totalSquared; 
} 

public static int cubedNumber(int totalSquared, int totalCubed){ 
    squaredNumber(totalSquared); 
    totalSquared = (int) Math.sqrt(totalSquared * totalSquared); 
    System.out.println(totalSquared); 
    totalCubed = totalSquared; 
    totalCubed = (int) Math.pow (numSquare, 3); 
    return totalCubed; 
} 

} 

的方法cubedNumber似乎返回0。 任何幫助是極大的讚賞。請原諒我的基本代碼。這是一堂課。

這是答案。再次感謝你。

import java.util.*; 
public class ExamPaper2011 
{ 
public static void main(String [] args){ 

    Scanner in = new Scanner(System.in); 

    System.out.print("Please enter a number to square and cube: "); 
    int n = in.nextInt(); 

    cubedNumber(n); 

} 

public static int squaredNumber(int n){//Question 4 
    System.out.println("You entered " + n); 
    n = n * n; 
    System.out.println("Squared = " + n); 
    return n; 
} 

public static int cubedNumber(int n){ 
    squaredNumber(n); 
    n = n * squaredNumber(n); 
    System.out.println("Cubed = " + n); 
    return n; 
} 

} 

我很欣賞這個好評。真的有幫助。謝謝你們。

+1

不會立方乘以原始數量的平方倍嗎?你爲什麼要取平方根的平方根? – 2013-02-18 18:06:47

+1

你的數學是錯誤的。你試圖做'5^2^3'(立方值)。你說你想要'5^2'和'5^3'。 – 2013-02-18 18:06:58

+0

哦,是的,我明白了。非常感謝。 – PrimalScientist 2013-02-18 18:08:17

回答

1

如何將用戶輸入檢查部分移出邏輯方法?

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

     Scanner in = new Scanner(System.in); 

     System.out.print("Please enter a number: "); 
     //here you get user input, maybe ask user what calculation he wants to do ^2 Or ^3 
     //...get n from user input. 
     //if he wants square 
     print squaredNumber(n); 
     //if he wants cubed 
     print cubedNumber(n); 
    } 

    public static int squaredNumber(int n){ 
     return n*n; 

    } 

    public static int cubedNumber(int n){ 
     return n*squaredNumber(n); 
    } 

} 
+0

這太棒了,謝謝Kent。 我不知道爲什麼我試圖使用Math.sqrt。背後的想法是試圖將平方數恢復到原來的int(在這種情況下爲5),然後使用5^3.我顯然是錯的,但這是我們學習的方式。儘管如此,謝謝。 我現在明白了。 =] – PrimalScientist 2013-02-18 18:18:45

+1

爲了簡單起見,我可能會使用'n * n * n'作爲'cubedNumber'方法,或許速度。 – syb0rg 2013-02-18 18:19:50

+1

@ syb0rg重用'squredmethod()'是OP的問題的一個要求。 ''我需要從cube方法中調用方法來返回多維數據集結果「' – Kent 2013-02-18 18:22:09

相關問題