2016-09-16 14 views
1

我對編程非常陌生,而且我在這個程序中遇到了麻煩,它希望用戶輸入一些名爲novas的「外星硬幣」,然後確定代表該數量所需的每個不同外星硬幣的最少數量,最高。這裏有硬幣和它們是什麼值得:如何確定代表輸入量所需的每個不同硬幣的最少數量?

  • 1極光= 60級的脈衝星
  • 1脈衝星= 70個引力
  • 1引力= 6個新星

下面是一個示例的輸入和輸出它應該是什麼樣子:

Enter number of novas: 64197 [Enter] 
That number of novas is equal to: 
2 auroras 
32 pulsars 
59 gravitons 
3 novas 

這是我的代碼:

import java.util.Scanner; 

public class AlienMoney { 
    public static void main(String[] args){ 
     int startAmount, amount, auroras, pulsars, gravitons, novas; 
     Scanner input = new Scanner(System.in); 
     System.out.print("Enter number of novas: "); 
     amount = input.nextInt(); 
     System.out.println("That number of novas is equal to: "); 

     startAmount = amount; 
     gravitons = amount/6; 
     amount = amount % 6; 
     pulsars = amount/70; 
     amount = amount % 70; 
     auroras = amount/60; 
     amount = amount % 60; 
     novas = amount; 

     System.out.println(auroras + " auroras"); 
     System.out.println(pulsars + " pulsars"); 
     System.out.println(gravitons + " gravitons"); 
     System.out.println(novas + " novas"); 


    } 
} 

這是我的輸出:

Enter number of novas: 64197 [Enter] 
That number of novas is equal to: 
0 auroras 
0 pulsars 
10699 gravitons 
3 novas 

我不知道我做錯了。我知道我絕對必須使用模數運算符%來獲得餘數,但我不確定在此之後要做什麼。我將不勝感激任何人的幫助。謝謝。

回答

1

您需要從最大的開始按正確的順序計算您的貨幣。

所以: 極光>脈衝星>引力>新星

相反的: 引力>脈衝星>極光>新星

+1

這個解釋是正確的。下次包含代碼以獲得更好的結果。 –

-1

就在這裏,問題的線條評論表示:

startAmount = amount; 
gravitons = amount/6; 
amount = amount % 6; 
pulsars = amount/70; // <-- starts here 
amount = amount % 70; 
auroras = amount/60; 
amount = amount % 60; 
novas = amount; 

你'正在使用錯誤的變量。使用您分配所需的量到不是變量,例如:

startAmount = amount; 
gravitons = amount/6; 
amount %= 6; 
pulsars = gravitons/70; 
gravitons %= 70; 
auroras = pulsars/60; 
pulsars %= 60; 
novas = amount; // this doesn't need to change but there's no need to assign amount into a new variable 

而且使用%=操作。它太酷了。 ;)

+1

這是不正確的,因爲它指定較小的面額硬幣_first_,這會導致正在使用的_greatest_數量的新星硬幣。 –

+0

它*先*分配它們,但它也將它們轉換成更高的面額,所以它仍然有效。 – RamenChef

0

以下代碼片段中的方法是計算三個硬幣中每個硬幣的novas數量,然後計算每個硬幣用來表示輸入數量的數量。

爲了使用最少數量的硬幣,我們應該開始儘可能多地使用極光,其餘爲脈衝星,其次爲引力子。

int auroras = amount/(6 * 70 * 60); 
int remainder = amount % (6 * 70 * 60); 
int pulsars = remainder/(6 * 70); 
remainder = remainder % (6 * 70); 
int graviton = remainder/6; 
int novas = remainder % 6; 
相關問題