>我有一个简单的程序,其中程序从文件接收输入并将十进制转换为二进制并以二进制形式计算一的数量?现在对于小值没关系而对于像15755645551这样的巨大价值,它显然是行不通的。有人知道如何解决这个问题吗?任何人都可以尝试使用我的代码吗?谢谢!!这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#define BUFFER 25
long number_read = 0;
long number_of_ones = 0;
long remainder_value = 0;
long binary = 0;
long base = 0;
long buff[BUFFER];
int main()
{
FILE *fp; //file pointer fp
fp = fopen("File.txt", "r+");
while (fgets(buff, sizeof(buff), fp) != NULL)
{
number_read = atoi(buff); //ASCII to integer
printf("nnumber is=%d", number_read);
while (number_read > 0)
{
remainder_value = number_read % 2;
/* To count no.of 1s */
if (remainder_value == 1)
{
number_of_ones++;
}
binary = binary + remainder_value * base;
number_read = number_read / 2;
base = base * 10;
}
printf("nNo.of 1's in It's binary representation is = %dn", number_of_ones);
number_of_ones = 0;
}
fclose(fp);
return 0;
}
因为"long"类型作为"int"类型占用4个字节。您应该将其更改为"长长"类型。