我编写了这个简单的加密程序:
public static void main(String[] args) {
int password = 123456789;
int firstLayer = password / 58;
int secondLayer = firstLayer * 23;
int thirdLayer = secondLayer + 85;
System.out.println(thirdLayer);
int encryptedPassword = thirdLayer;
int thirdLayerD = encryptedPassword - 85;
int secondLayerD = thirdLayerD / 23;
int firstLayerD = secondLayerD * 58;
System.out.println(firstLayerD);
}
但我有一个奇怪的问题。解密密码后,我得到:123456770
我希望获得与原版相同的密码,但我不知道问题所在。
答案 0 :(得分:1)
这是因为123456789/58 = 2128565,32759,这会被截断为一个int。
答案 1 :(得分:0)
整数除法运算导致截断任何余数。
使用double
,然后再次调用Math.round()
生成整数:
public static void main(String[] args) {
int password = 123456789;
double firstLayer = password / 58d;
double secondLayer = firstLayer * 23;
double thirdLayer = secondLayer + 85;
double encryptedPassword = thirdLayer;
double thirdLayerD = encryptedPassword - 85;
double secondLayerD = thirdLayerD / 23;
int firstLayerD = (int)Math.round(secondLayerD * 58);
System.out.println(firstLayerD);
}
输出:
123456789