题目地址:https://pintia.cn/problem-sets/994805260223102976/problems/994805284923359232
题目描述:
如果你是哈利·波特迷,你会知道魔法世界有它自己的货币系统 —— 就如海格告诉哈利的:“十七个银西可(Sickle)兑一个加隆(Galleon),二十九个纳特(Knut)兑一个西可,很容易。”现在,给定哈利应付的价钱 P 和他实付的钱 A,你的任务是写一个程序来计算他应该被找的零钱。
-
输入格式:
输入在 1 行中分别给出 P 和 A,格式为 Galleon.Sickle.Knut,其间用 1 个空格分隔。这里 Galleon 是 [0, 10^7 ] 区间内的整数,Sickle 是 [0, 17) 区间内的整数,Knut 是 [0, 29) 区间内的整数。 -
输出格式:
在一行中用与输入同样的格式输出哈利应该被找的零钱。如果他没带够钱,那么输出的应该是负数。
解题思路:
这道题首先因为输入格式为 Galleon.Sickle.Knut,所以想到使用字符串去接收,之后通过调用split方法以"."为分割符将输入的字符串分割后转换为int型进行计算即可
易错点:当P==A时输出的应该是0.0.0而不是0
程序:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String P,A;
Scanner sc = new Scanner(System.in);
P=sc.next();
A=sc.next();
String[] P1 = P.split("\\.");
String[] A1 = A.split("\\.");
int tempP = (Integer.parseInt(P1[0])*17+Integer.parseInt(P1[1]))*29+Integer.parseInt(P1[2]);
int tempA = (Integer.parseInt(A1[0])*17+Integer.parseInt(A1[1]))*29+Integer.parseInt(A1[2]);
int r1,r2,r3;
r1=(tempA-tempP)/493;
r2=(tempA-tempP-r1*493)/29;
r3=(tempA-tempP-r1*493-r2*29);
if (tempA>=tempP) {
System.out.println(r1+"."+r2+"."+r3);
}else {
System.out.println("-"+Math.abs(r1)+"."+Math.abs(r2)+"."+Math.abs(r3));
}
}
}