gpt4 book ai didi

c - 函数不返回 long long int

转载 作者:行者123 更新时间:2023-11-30 15:01:05 26 4
gpt4 key购买 nike

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

最佳答案

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

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

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

关于c - 函数不返回 long long int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41703669/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com