Python vs C:不同的输出

时间:2013-05-31 17:02:40

标签: c++ python 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代码给出了正确的输出。我觉得它与模数有关,但我无法弄明白。请帮忙!谢谢!

2 个答案:

答案 0 :(得分:3)

在C代码中,您应该使用int类型。 char类型的范围仅为0到255.

char a = num / 1296;
char ar = num % 1296;
char b = ar / 36;
char c = ar % 36; the C code 

答案 1 :(得分:2)

问题是您在char函数中使用void largeNumToKeyboard(int num)类型,并且您正在测试的值可能会溢出char。您需要至少将前三个更改为int ...

void largeNumToKeyboard(int num) {
    int a = num / 1296;
    int ar = num % 1296;
    int 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 9 24