簡體   English   中英

不同語言中相同算法的不同輸出

[英]Different outputs for same algorithm in different languages

Java 源代碼:

package n1_problem;

/**
 *
 * @author nAwS
 */
public class loop {

    int loop(long i)
    {
        long n=i;
        int count=1;
        while(n>1){
            if(n%2==0){
                n=n/2;
            }
            else{
                n=3*n+1;
            }
            count++;
        }
       return count; 
    }

    int max_cycle(long j,long k){

        int max=-1;
        for(long i=j;i<=k;i++){
            int count=loop(i);
            if(count>max){
                max=count;
            }
        }
        return max;
    }


}


public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        loop lp=new loop();
        System.out.println("Max Cycle:"+lp.max_cycle(1,1000000));
    }

}

C源代碼:

int main()
{
    long r,h;
    int f=0;
    do 
    {
        printf("Value,r:");
        scanf("%ld",&r);
        printf("Value,h:");
        scanf("%ld",&h);

        f=max_cycle(r,h);
        printf("Max:%d\n",f);

    }while(getch()!='e');
}

int loop(long i)
{
        long n=i;
        int count=1;
        while(n>1)
        {
            if(n%2==0){
                n=n/2;
            }
            else{
                n=3*n+1;
            }
            count++;
        }
       return count; 
    }

    int max_cycle(long j,long k)
    {

        int max=1;
        long i=0;
        for(i=j;i<=k;i++){

            int count=loop(i);
            if(count>max){
                max=count;
            }
        }
        return max;
    }

對於 3n+1 問題算法,這兩個代碼之間沒有邏輯上的區別。唯一的問題是在 C 中它給出 476 作為最大循環數,而在 java 中它是 525...為什么?

在大多數 C 編譯器中long通常定義為 4 字節 integer( long int的縮寫)。 在 Java 中, long定義為 8 字節 integer。

You can change your Java code to use int for a 4-byte integer, or use long long in your c program for an 8-byte integer (I think this was added in C99, it may or may not be available on your compiler) .

Java代碼中,在方法max_cycle(long j,long k)中, max被初始化為-1 ,而在C代碼中它是1 只需檢查這是否導致邏輯錯誤。

Java 定義了 integer 類型的大小和表示,C 沒有。 在 Java 中, long是 64 位 2 的補碼數。 在 C 中,它至少是 32 位,也許更多,並且可以是有符號的、無符號的、1 的補碼、2 的補碼、符號和幅度或其他。

您是否注意到,如果您更改 Java 代碼的這一行

long n = i;

對此

int n = (int)i;

您得到與 C 代碼相同的結果嗎? 可能您在 2 的補碼機器上,並且您的 C 編譯器決定long是 32 位。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM