【发布时间】: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