【问题标题】:function doesn't return long long int函数不返回 long long int
【发布时间】:2023-03-29 20:37:01
【问题描述】:

我不知道为什么我的函数没有给出正确的结果。我怀疑它没有返回正确的类型(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

【问题讨论】:

  • 为什么i 在你的dec2bin 中突然声明为int,而其他都是unsigned long long?这可能是溢出并导致错误结果的变量,而不是您对“返回int”函数的完全没有根据的怀疑。
  • 而且您并没有真正转换为二进制,而是“转换”为不同的十进制数。
  • 没错。另一个问题是:你到底想在这个函数中做什么?您正在生成一个数字,其十进制表示“看起来像”二进制表示。那是你真正想做的吗?这种转换的意义何在?
  • 请使用输出的文本编辑您的帖子,而不是屏幕截图。屏幕快照通常用于 GUI 或图形输出。
  • C++ 标签是否正确?您的文件具有“.c”扩展名。您的头文件使用 C 标准库。您的输入和输出使用 C 语言函数。为什么这段代码是 C++? (注意:C 和 C++ 是不同的语言。)

标签: c


【解决方案1】:

您不能通过这种方式将数字转换为二进制,十进制和二进制是同一数字的外部表示。您应该将该数字转换为 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);
}

【讨论】:

  • 这是一个合理的建议,但不是问题的答案。为什么你说字符串然后使用char *?为什么你声明结果超出了你的条件范围?这几乎是C风格。就像指针算术和 *--p = ... 东西一样。而是专注于可读性。
  • @Aziuth:这个问题被标记为 C 和 C++。 OP 使用纯 C,我用 C 代码回答。我确信有一些 C++ 解决方案可以放在一行或更多 : 上。
  • 啊,没看到双标签,我的错。
猜你喜欢
  • 2014-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-10
  • 2015-08-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多