2014-12-23 69 views
0

羅馬數字計算器將無法正常工作時,計算器的結果爲負數, 我真的不知道如何解決它。 當計算器給出一個正值一切正常 例如結果會是這樣如何獲得一個羅馬數字計算器與負數

please enter the two two integer values that you want to vomplete the operation with 
> 33 
> 44 
please enter the operation you want preformed 
> + 
Here is the answer 77 negative roman numeral value Here is the answer in roman numerals 
LXXVII 

代碼在這裏:

public static void main(String[] args) { 
    System.out.println("please enter the two two integer values that you want" 
      + " to vomplete the operation with "); 
    Scanner scan = new Scanner(System.in); 
    int first = scan.nextInt(); 
    int sec = scan.nextInt(); 
    System.out.println(" please enter the operation you want preformed"); 
    String opera = scan.next(); 
    System.out.println(" Here is the answer"); 
    int value = Acalc(opera, first, sec); 
    String roman = Roman(value); 
    System.out.println(" Here is the answer in roman numerals "); 
    System.out.println(roman);    
} 

public static int Acalc(String opera, int n1, int n2){ 
    int result = 0; 
    //Write the calulator 

if (opera.equals("+")) {result=n1+n2;} 

if (opera.equals("-")) {result=n1-n2;} 

if (opera.equals("*")) {result=n1*n2;} 

if (opera.equals("/")) {result=n1/n2;} 

System.out.println(result); 

return result; 
} 

public static String Roman(double input){ 

    String s = ""; 

    if (input <1 || input < 999) 
    System.out.println("negative roman numeral value "); 

    while (input >= 100) { 
    s += "C"; 
    input -= 100; 
    } 
    while (input >= 90) { 
    s += "XC"; 
    input -= 90; 
    } 
    while (input >= 50) { 
    s += "L"; 
    input -= 50; 
    } 
    while (input >= 40) { 
    s += "XL"; 
    input -= 40; 
    } 
    while (input >= 10) { 
    s += "X"; 
    input -= 10; 
    } 
    while (input >= 9) { 
    s += "IX"; 
    input -= 9; 
    } 
    while (input >= 5) { 
    s += "V"; 
    input -= 5; 
    } 
    while (input >= 4) { 
    s += "IV"; 
    input -= 4; 
    } 
    while (input >= 1) { 
    s += "I"; 
    input -= 1; 
    } 
    return s; 
} 
+1

羅馬人甚至有負數嗎? – paxdiablo

+1

訣竅是實現II的補碼算術。 –

+0

羅馬數字不能表示負數,也不能爲零。 –

回答

3

那麼它是什麼價值,羅馬數字不能代表零個或負數,但下面的編輯應該讓你的程序去做。

如果您有:

if (input <1 || input < 999) 
    System.out.println("negative roman numeral value "); 

用途:

if (input < 0){ 
    s="-"; 
    input *= -1; 
} 
else if (input > 999) 
    return "Output too large"; 
else if (input == 0) 
    return "nulla"; 

法無在拉丁語中是零,因爲羅馬數字相當於不存在。

1

這是不工作的原因是因爲當result爲負是因爲做input -= #沒有意義,因爲這會使結果更負面。應改爲input += #。但是,這會爲代碼添加相當多的工作/長度。

取而代之,是否可以存儲result是正數還是負數?然後,如果結果爲負數,可以將其更改爲正數,然後轉換爲羅馬數字,然後在s前添加負號。

例如:

orig_result = acalc(some parameters) 

if (orig_result > 0){ 
    result = result 
} 
if (orig_result < 0){ 
    result = result * -1 
} 

//Convert to roman numerals 

if (orig_result < 0){ 
    s = "-" + s 
}