过去两个小时左右我一直在研究这个问题而且遇到了障碍。我实际上可以执行除法,但是当需要打印非0的余数时输出不匹配。我想知道我做错了什么。
public class Division {
public static void main(String[] args) {
int numerator = 0;
int numeratorprint = 0;
int denominator = 0;
int product = 0;
int remainder = 0;
int counter = 1;
Scanner input;
input = new Scanner(System.in);
System.out.print("Enter two positive intergers for division:\n");
numerator = input.nextInt();
numeratorprint = numerator;
denominator = input.nextInt();
while ((numerator < 0) || (denominator < 0)) {
System.out.print("Enter two positive intergers for division:\n");
numerator = input.nextInt();
denominator = input.nextInt();
}
if (numerator == 0){
System.out.print(numerator + "/" + denominator + " = " + numerator + " with a remainder of " + numerator);
}
else if (denominator == 0){
System.out.print("This result is undefined (Cannot divide by Zero)");
}
else if (denominator > numerator){
System.out.print("Cannot do proper fractions");
}
else {
while (numerator > denominator){
counter++;
numerator = numerator - denominator;
}
}
product = counter * denominator;
remainder = numeratorprint - product;
System.out.println(numeratorprint + " / " + denominator + " = " + counter + " with a remainder of " + remainder);
}
}
/* Sample I/O 1
Enter two positive intergers for division:
25
5
OUTPUT:
25 / 5 = 5 with a remainder of 0
Sample I/O 2
Enter two positive intergers for division:
27
5
OUTPUT:
27 / 5 = 6 with a remainder of -3
*/
答案 0 :(得分:0)
我相信你有一个错误,你在1而不是0开始你的计数器。我测试了一些数字,改变这似乎解决它就好了。所以改变
int counter = 1;
到
int counter = 0;
此外,您必须将else块的条件更改为
while (numerator >= denominator) {...
以说明除数何时均分红利的情况。
答案 1 :(得分:0)
我在代码中看到了一些错误。 1.冗余变量 2为什么不使用模块化操作员? 3.你也可以删除一个while循环
rails generate migration AddTypeDeliveryToProducts type_delivery:integer
class AddTypeDeliveryToProducts < ActiveRecord::Migration[5.1]
def change
add_column :products, :type_delivery, :integer, array:true, default: [], limit: 8
end
end
class Product < ApplicationRecord
enum type_delivery: { a: 1, b: 2, c: 3, d: 4 }
end