[英]function doesn't return long long int
我不知道為什么我的函數沒有給出正確的結果。 我懷疑它沒有返回正確的類型(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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.