带小数点的10进制转2进制c语言完整代码
时间: 2023-11-01 20:06:27 浏览: 81
以下是带小数点的10进制转2进制的C语言完整代码:
```c
#include <stdio.h>
int main() {
float decimal;
int integerPart, binaryInteger = 0, binaryFraction = 0, i = 1, j;
float fractionPart, binaryFactor = 0.1;
printf("Enter a decimal number: ");
scanf("%f", &decimal);
integerPart = (int)decimal;
fractionPart = decimal - integerPart;
while (integerPart != 0) {
binaryInteger += (integerPart % 2) * i;
integerPart /= 2;
i *= 10;
}
while (fractionPart != 0 && j < 10) {
fractionPart *= 2;
binaryFraction = binaryFraction * 10 + (int)fractionPart;
fractionPart -= (int)fractionPart;
j++;
}
printf("Binary equivalent = %d.%d\n", binaryInteger, binaryFraction);
return 0;
}
```
这个代码可以将用户输入的带小数点的10进制数转换成2进制数并输出。在代码中,我们先读入用户输入的10进制数,然后把它分成整数部分和小数部分。对于整数部分,我们通过不断把它除以2来得到2进制数的每一位,并把每一位乘以相应的位权,最后把它们加起来即可得到整数部分的2进制数。对于小数部分,我们通过不断把它乘以2来得到2进制数的每一位,并把每一位乘以相应的位权,最后把它们加起来即可得到小数部分的2进制数。注意,在这个代码中,我们只保留小数部分的前10位。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)