所以基本上,$1.26 如何变成:
Dollars: 1
Quarters: 1
Pennies: 1
谢谢!将标题编辑为余数而不是模运算符
int change = (int)(changeDue*100);
int dollars = (int)(change/100);
change=change%100;
int quarters = (int)(change/25);
change=change%25;
int pennies = (int)(change/1);
change=change%1
System.out.println("Dollars: " + dollars);
System.out.println("Quarters: " + quarters);
System.out.println("Pennies: " + pennies);
模运算给出除法的其余部分。% 运算a % m
中的值始终介于 0
到 m - 1
之间。
change=change%100; // divides by 100 and leaves the remainder which is less than a dollar
change=change%25; // divides by 25 and leaves the remainder which is less than a quarter
change=change%10; // divides by 10 and leaves the remainder which is less than a dime
change=change%5; // divides by 5 and leaves the remainder which is less than a nickel
change=change%1 // this operation is always 0 because an integer can always be divided by 1 without a remainder
对于每个面额,您需要进行整数除法,然后取模:
-
整数除法忽略除法提醒,例如 126/100=1
-
模数只返回除法的提醒,例如 126%100=26
所以对于 126 美分,你需要 1 美元。并为每个较小的面额重复相同的提醒值。对于季度,您将获得 26/25=1 个季度,提醒为 26%1,即 1...你明白了。