![](/img/trans.png)
[英]Enhanced for-loop seems to be going through all elements at once. But is it supposed to or is my code wrong?
[英]My for loop increment seems to be wrong
我正在為大學密碼學做一個問題。 我的程序的一部分是,我希望獲得x等於(2744 ^ x)%24852977 = 8414508的冪。我有一個循環,使倍數增加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增量沒有確切的表示,並且會出現舍入誤差。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.