函数不返回long long int

时间:2017-01-17 17:44:51

标签: c

我不知道为什么我的功能没有给出正确的结果。我怀疑它没有返回正确的类型(unsigned long long int),但它返回一个int。

#include <stdlib.h>
#include <stdio.h>
#include <math.h>

// compile with:
//         gcc prog_long_long.c -o prog_long_long.exe
// run with:
//         prog_long_long

unsigned long long int dec2bin(unsigned long long int);

int main() {
    unsigned long long int d, result;

    printf("Enter an Integer\n");

    scanf("%llu", &d);

    result = dec2bin(d);

    printf("The number in binary is %llu\n", result);

    system("pause");

    return 0;
}

unsigned long long int dec2bin(unsigned long long int n) {
    unsigned long long int rem;
    unsigned long long int bin = 0;
    int i = 1;
    while (n != 0) {
        rem = n % 2;
        n = n / 2;
        bin = bin + (rem * i);
        i = i * 10;
    }
    return bin;
}

以下是具有不同输入值的结果的输出:

C:\Users\desktop\Desktop\gcc prog_long_long.c -o prog_long_long.exe

C:\Users\desktop\Desktop\prog_long_long
Enter an Integer
1023
The number in binary is 1111111111
The number in octal is 1777

C:\Users\desktop\Desktop\prog_long_long
Enter an Integer
1024
The number in binary is 1410065408
The number in octal is 2994

1 个答案:

答案 0 :(得分:1)

您不能以这种方式将数字转换为二进制,十进制和二进制是相同数字的外部表示。您应该将数字转换为C字符串,从右到左一次计算一个二进制数字。

以下是64位长long的工作原理:

#include <stdio.h>
#include <string.h>

char *dec2bin(char *dest, unsigned long long int n);

int main(void) {
    unsigned long long int d;
    char buf[65], *result;

    printf("Enter an Integer\n");

    if (scanf("%llu", &d) == 1) {
        result = dec2bin(buf, d);
        printf("The number in binary is %s\n", result);
    }

    //system("pause");

    return 0;
}

char *dec2bin(char *dest, unsigned long long int n) {
    char buf[65];
    char *p = buf + sizeof(buf);

    *--p = '\0';
    while (n > 1) {
        *--p = (char)('0' + (n % 2));
        n = n / 2;
    }
    *--p = (char)('0' + n);
    return strcpy(dest, p);
}
相关问题