得到答案作为余数而不是商

时间:2013-11-07 02:06:46

标签: java

当我运行它时,我得到了这个:

Enter 2 Integers, Do note that you will Get a Quotient and a Remainder.
Enter the First Number: 3
Now enter the Second Number: 9
Your Quotient is: 0
Your Remainder is: 3

应该是:

Enter 2 Integers, Do note that you will Get a Quotient and a Remainder.
Enter the First Number: 3
Now enter the Second Number: 9
Your Quotient is: 3
Your Remainder is: 0

代码:

import java.util.Scanner;
public class Remainder {
    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        int a = 0, b = 0, quotient, remainder;
        int smallerNumber = 0;
        int biggerNumber = 0;

        System.out.println("Enter 2 Integers, Do note that you will Get a Quotient and a Remainder.");
        System.out.print("Enter the First Number: ");
        a = reader.nextInt();
        System.out.print("Now enter the Second Number: ");
        b = reader.nextInt();

        remainder = (a % b);

        quotient = (a / b);
        remainder = (a % b);

        if(a > b){
            biggerNumber = a;
            a = b;
        }else{
            smallerNumber = a;
            biggerNumber = b;
        }
        System.out.print("Your Quotient is: ");
        System.out.println(quotient);
        if (remainder > 0){
            System.out.print("Your Remainder is: ");
            System.out.println(remainder);
        }
    }
}

2 个答案:

答案 0 :(得分:3)

您输入的数字顺序错误。您正在执行a / b,并且整数数学中的3 / 9为零。先输入9,然后输入3秒,事情就会起作用。

另请注意,在计算余数和商数后,您正在寻找更大和更小的数字(并且计算前者两次)。交换代码的顺序,然后除bigger/smaller以获得更好的结果......

  System.out.println("Enter 2 Integers, Do note that you will Get a Quotient and a Remainder.");
  System.out.print("Enter the First Number: ");
  a = reader.nextInt();
  System.out.print("Now enter the Second Number: ");
  b = reader.nextInt();

  if(a > b){
      biggerNumber = a;
      smallerNumber = b;
  } 
  else {
      smallerNumber = a;
      biggerNumber = b;
  }
  remainder = biggerNumber % smallerNumber;
  quotient = biggerNumber / smallerNumber;

答案 1 :(得分:0)

你有a和b倒退。相反,

quotient = b / a;
remainder = b % a; 

此外,a和b应该可以重命名为第一和第二......