как заставить калькулятор римских цифр работать с отрицательными числами

Калькулятор римских цифр не будет работать, когда результат калькулятора будет отрицательным, я, честно говоря, не знаю, как это исправить. Когда калькулятор выдает положительное значение все работает нормально например результат будет выглядеть так

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;
}

person Laura Herrera    schedule 23.12.2014    source источник
comment
Были ли у римлян вообще были отрицательные числа?   -  person paxdiablo    schedule 23.12.2014
comment
Хитрость заключается в реализации арифметики дополнений II.   -  person Hot Licks    schedule 23.12.2014
comment
Римские цифры не могли выражать ни отрицания, ни ноль.   -  person rp.beltran    schedule 23.12.2014
comment
Можете ли вы объяснить эту строку? if (input <1 || input < 999)   -  person Paul Hicks    schedule 23.12.2014
comment
гугл говорит нет, но мой учитель информатики говорит иначе   -  person Laura Herrera    schedule 23.12.2014
comment
@HotLicks, ты должен мне новую клавиатуру, потому что обмочил текущую, пока я нюхал кофе, читая твой комментарий :-)   -  person paxdiablo    schedule 23.12.2014
comment
Вы сказали, что он отлично работает для положительных ответов, но в опубликованном вами примере он печатает «отрицательное значение римской цифры», когда ответ равен 77. Это ошибка в вашем сообщении или в самой программе?   -  person rp.beltran    schedule 23.12.2014
comment
@rp, это из-за ошибки, на которую указал Пол. 77 меньше 999, поэтому он выводит эту строку (и продолжает, чего, вероятно, не должно быть).   -  person paxdiablo    schedule 23.12.2014


Ответы (2)


Итак, как бы там ни было, римские цифры не могут представлять ноль или отрицательные числа, но следующие изменения должны позволить вашей программе сделать это.

Где у вас есть:

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";

Nulla на латыни означает ноль, поскольку эквивалента римской цифры не существует.

person rp.beltran    schedule 23.12.2014

Причина, по которой это не работает, заключается в том, что когда 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
}
person KingOfTheNerds    schedule 23.12.2014