Python vs C:不同的输出

我有一个小程序,可以将以10为底的数字转换为以36为底的数字。这是Python代码,它可以按预期工作。


def numToKey(num):

    start = 0x04;

    i = 0;

    for i in range(0,num):

        start+=1

    return start;



def largeNumToKeyboard(num):

    a = num / 1296;

    ar = num % 1296;

    b = ar / 36;

    c = ar % 36;


    a = numToKey(a);

    b = numToKey(b);

    c = numToKey(c);


    newb = b;

    if(a == b):

        newb = 0x2D;


    if(c == b):

        c = 0x2E;



    print a,newb,c

    print


largeNumToKeyboard(0)

largeNumToKeyboard(200)

输出是


4 45 46

4 9 24

“ 4 45 46”正确表示0,而“ 4 9 24”正确表示200。


但是问题是,在将其转换为C代码后,它停止工作。


#include <stdio.h>


int main(int argc, char **argv)

{

    printf("hello world\n");

    largeNumToKeyboard(0);

    largeNumToKeyboard(200);

    return 0;

}


char numToKey(char num) {

    char start = 0x04;

    char i = 0;

    for (i = 0; i < num; i++) {

        start++;

    }

    return start;

}


void largeNumToKeyboard(int num) {

    char a = num / 1296;

    char ar = num % 1296;

    char b = ar / 36;

    char c = ar % 36;


    a = numToKey(a);

    b = numToKey(b);

    c = numToKey(c);

    char newb = b;

    if(a == b){

        newb = 0x2D;

    }

    if(c == b){

        c = 0x2E;

    }

    printf("%d ",a);

    printf("%d ",newb);

    printf("%d\r\n",c);


}

现在的输出是


4 45 46

4 45 46

我不明白为什么对于200的输入,C代码给我错误的输出,但是python代码给我正确的输出。我感觉它与模数有关,但我无法弄清楚。请帮忙!谢谢!


FFIVE
浏览 166回答 3
3回答

慕尼黑8549860

问题是您char在void largeNumToKeyboard(int num)函数中使用了类型,而正在测试的值可能会导致溢出char。您至少需要将前三个更改为int...void largeNumToKeyboard(int num) {&nbsp; &nbsp; int a = num / 1296;&nbsp; &nbsp; int ar = num % 1296;&nbsp; &nbsp; int b = ar / 36;&nbsp; &nbsp; char c = ar % 36;&nbsp; &nbsp; a = numToKey(a);&nbsp; &nbsp; b = numToKey(b);&nbsp; &nbsp; c = numToKey(c);&nbsp; &nbsp; char newb = b;&nbsp; &nbsp; if(a == b){&nbsp; &nbsp; &nbsp; &nbsp; newb = 0x2D;&nbsp; &nbsp; }&nbsp; &nbsp; if(c == b){&nbsp; &nbsp; &nbsp; &nbsp; c = 0x2E;&nbsp; &nbsp; }&nbsp; &nbsp; printf("%d ",a);&nbsp; &nbsp; printf("%d ",newb);&nbsp; &nbsp; printf("%d\r\n",c);}...然后打印输出...4 45 464 9 24
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python