我的 for 循环增量似乎是错误的
My for loop increment seems to be wrong
我正在为大学做一道密码学题。我的程序的一部分是我想要获得 x 的幂,使得 (2744^x) % 24852977 = 8414508。我有一个循环将 double 增加 0.001。我的问题是:不是每次循环都增加 0.001,而是在小数位显示更长的数字。这与长 MIN/MAX 值有关吗?如果是这样,我该如何解决这个问题,或者谁能解释我哪里出错了?这是我的增量示例。如何获得小数点后 4 位的截止点。
10.276999999989387
10.277099999989387
10.277199999989387
10.277299999989387
10.277399999989386
10.277499999989386
10.277599999989386
10.277699999989386
10.277799999989385
import java.lang.*;
public class crypt {
public static void main(String args[])
{
long p =24852977;//variables
long g = 2744;
long sum = 8414508;
long c1 = 15268076;
long c2 = 743675;
for(double i=0; i<=p; i=i+0.0001)//loop for increasing the power in next part of the program
{
long num=(long)(Math.pow((long)g, i));//number = g to the power of i
System.out.println(i);// just to check
if(num % p == sum)//my equation
{
System.out.println(i);//print the power that satisfy's this
}
}
}
}
请记住,数字的内部表示是二进制的。因此,不一定每个十进制数都有精确的二进制表示。也就是说,没有精确表示您的 0.0001 增量,预计会出现舍入误差。
我正在为大学做一道密码学题。我的程序的一部分是我想要获得 x 的幂,使得 (2744^x) % 24852977 = 8414508。我有一个循环将 double 增加 0.001。我的问题是:不是每次循环都增加 0.001,而是在小数位显示更长的数字。这与长 MIN/MAX 值有关吗?如果是这样,我该如何解决这个问题,或者谁能解释我哪里出错了?这是我的增量示例。如何获得小数点后 4 位的截止点。
10.276999999989387 10.277099999989387 10.277199999989387 10.277299999989387 10.277399999989386 10.277499999989386 10.277599999989386 10.277699999989386 10.277799999989385
import java.lang.*;
public class crypt {
public static void main(String args[])
{
long p =24852977;//variables
long g = 2744;
long sum = 8414508;
long c1 = 15268076;
long c2 = 743675;
for(double i=0; i<=p; i=i+0.0001)//loop for increasing the power in next part of the program
{
long num=(long)(Math.pow((long)g, i));//number = g to the power of i
System.out.println(i);// just to check
if(num % p == sum)//my equation
{
System.out.println(i);//print the power that satisfy's this
}
}
}
}
请记住,数字的内部表示是二进制的。因此,不一定每个十进制数都有精确的二进制表示。也就是说,没有精确表示您的 0.0001 增量,预计会出现舍入误差。