C 函数不返回long int

C 函数不返回long int,c,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_lo

我不知道为什么我的函数不能给出正确的结果。我怀疑它没有返回正确的类型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字符串,从右到左一次计算一个二进制数字

下面是它在64位长整数中的工作原理:

#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);
}

为什么我突然在你的dec2bin中声明为int,而其他一切都是无符号的long-long?这可能是溢出并导致错误结果的变量,而不是你对函数返回int的毫无根据的怀疑。你不是真的转换为二进制,而是转换为不同的十进制数。确切地说。另一个问题是:你到底想在这个函数中做什么?您正在生成一个十进制表示形式类似于二进制表示形式的数字。这就是你真正想做的吗?这种转换的意义是什么?请用输出的文本而不是屏幕截图编辑您的文章。屏幕快照一般用于GUI或图形输出。C++标签是否正确?您的文件具有.c扩展名。头文件使用C标准库。您的输入和输出使用C语言函数。为什么这个代码是C++?注意:C和C++是不同的语言,这是一个很好的建议,但不是问题的答案。为什么要谈论字符串,然后使用char*?为什么你们要将结果声明在你们的条件范围之外?这差不多是C风格。就像指针算术和*-p=。。。东西将注意力放在可读性上。@阿齐乌斯:问题被标记为C和C++。OP使用纯C,我用C代码回答。我确信有C++解决方案适合于一行或多个:Ah k,没有看到双标签,我的坏。
#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);
}